#include "sk_form_gzltj.h"
#include "ui_sk_form_gzltj.h"
#include "pub_var.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include <QAxObject>
#include <QFile>
#include <QLibrary>
#include <windows.h>
#include <QItemDelegate>
#include <QAbstractItemDelegate>
/*
com_printer_setting 表的使用。
p_type : 打印类别，处方，挂号票，等。
p_item : 项目名称，
p_top， p_left，p_width，p_height 坐标定义

p_item_type 为 item，（p_top， p_left），（p_width，p_height）为区域左上角坐标和右下角坐标。

p_item_type 为 base，
    p_item = 页面 ，p_width，p_height 定义页面大小。
    p_item = 行 ，p_width，p_height为行上限坐标，下限坐标。
    p_item = 列 ，p_width，p_height为行左限坐标，右限坐标。
    行，列，意义可参考excel。
    p_item = line，  （p_top， p_left），（p_width，p_height）为线段起始坐标和终止坐标。

p_font_name ： 字体名称
p_font_size ： 字体大小，单位mm
p_position ： 对齐方式 0:左，1:中，2:右,
p_mode ：打印模式：1, p_print_item + 项目内容; 0, 只打印项目内容
p_print_item ：与打印模式相关。
p_item_type ： 项目类型， item 内容项目，base 基础项目

*/

const int MAX_LINES_BILL = 8; //sql语句包含记录条数
const int SQL_VALUE_COUNT = 50; //sql语句包含记录条数
const int MAX_EXPORT_FIELD_COUNT = 35;  //输出excel报表最大字段数量

Form_gzltj::Form_gzltj(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_gzltj)
{
    ui->setupUi(this);

    initial_finished = false;

    qrm = new QSqlQuery(pub::db_m);
    qrmp = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    QSettings setIni("clin.ini", QSettings::IniFormat);
    //恢复当前窗口状态
    QRect rct = setIni.value("windowState/gzltj").toRect();
    this->setGeometry(rct);
    ui->pb_export_to_excel->setEnabled(false);
    ui->grp_count_field->setEnabled(false);
    ui->ckb_group_name->setEnabled(false);
    ui->ckb_group_name->setChecked(false);

    //列表字体
    ui->tvItemList->setFont(this->font());

    ui->pbPrintOut->setEnabled(false);
    ui->pbBalance->setEnabled(false);

    QString printerName = setIni.value("sk/printer").toString(); //日结报表使用收款打印机

    //配置打印机
    prt= new QPrinter(QPrinter::HighResolution);
    prt->setPrinterName(printerName);

    //发票纸张大小设定
    qrm->exec("select p_width,p_height,p_item from com_printer_setting where "
              " p_item_type = 'base' and p_type = '收费日结' and p_item in('偏移', '页面','单元缩进')");
    double w = 0, h = 0;
    xPos = yPos = 0;

    while(qrm->next())
    {
        QString itm = qrm->value(2).toString() ;

        if( itm == "页面")
        {
            w = qrm->value(0).toDouble();
            h = qrm->value(1).toDouble();
        }else if(itm == "偏移"){
            xPos = qrm->value(0).toDouble();
            yPos = qrm->value(1).toDouble();
        }else if(itm == "单元缩进"){
            margin = qrm->value(0).toDouble();
        }
    }

    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());
    //QRectF szf = pglot.fullRect(QPageLayout::Point);

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4 ;

    prt->setOrientation(QPrinter::Portrait);      //Portrait 纵向打印, Landscape 横向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    //提取收款员列表
    sq = "select code, name from com_privileges where role_dept = '收款员'";
    qrm->exec(sq);

    qDebug()<<"提取收款员列表 ： "<<sq;
    if(qrm->size()<1)
    {
        QMessageBox::warning(NULL, "注意", "系统中找不到角色定义为‘收款员’的用户！");
    }
    else
    {
        ui->cbbOper->clear();
        ui->cbbOper->addItem("全部");
        ui->cbbOper_2->clear();
        ui->cbbOper_2->addItem("全部");
        QString opcd_dest, opcd_source;
        while(qrm->next())
        {
            ui->cbbOper->addItem(qrm->value(1).toString());
            ui->cbbOper_2->addItem(qrm->value(1).toString());
            opcd_dest = "000000";
            opcd_source = qrm->value(0).toString();
            opcd_dest.replace(6 - opcd_source.length(), opcd_source.length(), opcd_source);
            oper_code[qrm->value(1).toString()] = opcd_dest;
        }
    }

    //提取核算科室列表
    sq = "select dept_code, dept_name from COM_DEPARTMENT where dept_type = 'C' and valid_state = '1'";
    qrm->exec(sq);
    qDebug()<<"提取核算科室列表 ： "<<sq;
    if(qrm->size()<1)
    {
        QMessageBox::warning(NULL, "注意", "系统中找不有效的核算科室！");
    }
    else
    {
        ui->cbbDept->clear();
        ui->cbbDept->addItem("全部");
        ui->cbbDept->addItem("只看科室");
        while(qrm->next())
        {
            ui->cbbDept->addItem(qrm->value(1).toString());
            ui->cbb_dept_fee_detail->addItem(qrm->value(1).toString());
            dept_code[qrm->value(1).toString()] = qrm->value(0).toString();
        }
    }
    qDebug()<<dept_code;
    //提取险种列表

    sq = " select code, name from com_dict_com where dic_type = '险种'";
    qrm->exec(sq);
    qDebug()<<"提取险种列表 ： "<<sq;
    if(qrm->size()<1)
    {
        QMessageBox::warning(NULL, "注意", "系统中找不有效的险种！");
    }
    else
    {
        ui->cbbInsuType->clear();
        ui->cbbInsuType->addItem("全部");
        while(qrm->next())
        {
            ui->cbbInsuType->addItem(qrm->value(1).toString());
            insutype_code[qrm->value(1).toString()] = qrm->value(0).toString();
        }
    }

    //检索系统当前用户查询权限
    sq = "select role_dept from com_privileges where code = '" + pub::usr_code + "' and role_dept = '财务'";
    qDebug()<<"检索系统当前用户查询权限 : "<<sq;
    qrm->exec(sq);
    if(qrm->size() < 1)
    {
        ui->tab_3->setEnabled(false);
        ui->tab_4->setEnabled(false);
        ui->tab_5->setEnabled(false);
        ui->tab_6->setEnabled(false);
        ui->tab_7->setEnabled(false);
        ui->cbbOper_2->setVisible(false);
        privFinance = false;
    }
    else
    {
        ui->tab_3->setEnabled(true);
        ui->tab_4->setEnabled(true);
        ui->tab_5->setEnabled(true);
        ui->tab_6->setEnabled(true);
        ui->tab_7->setEnabled(true);
        ui->cbbOper_2->setVisible(true);
        privFinance = true;
    }

    ui->tabWidget->setCurrentIndex(0);
    //挂号查询临时表
    sq = "create temporary table if not exists tmp_balance_opr (操作员 varchar(20), 起始时间 varchar(30),"
         " 截止时间 varchar(30), 日结时间 varchar(30), 挂号人次 int,  挂号费 varchar(30), "
         " 检查费 varchar(30),  诊察费 varchar(30),  其它 varchar(30), 现金 varchar(30),"
         " 账户 varchar(30),  统筹 varchar(30), ord int auto_increment PRIMARY key)";
    if(!qrm->exec(sq))
    {
        QMessageBox::warning(NULL, "注意", " tmp_balance_opr 创建表失败！");
        ui->tab_3->setEnabled(false);
    }

    //收费查询临时表
    sq = "create temporary table if not exists tmp_balance_opb (操作员 varchar(20), 起始时间 varchar(30),"
         " 截止时间 varchar(30), 日结时间 varchar(30), 票据张数 varchar(30),  合计金额 varchar(30), "
         " 现金金额 varchar(30),  账户金额 varchar(30), 统筹金额 varchar(30), ord int auto_increment PRIMARY key)";
    if(!qrm->exec(sq))
    {
        QMessageBox::warning(NULL, "注意", " tmp_balance_opb 创建表失败！");
        qDebug()<<sq;
        ui->tab_3->setEnabled(false);
    }

    //提取费用类别
    QString sql_str = "";
    sq = "select name from com_dict_com where dic_type = 'MINFEE'";
    qrm->exec(sq);
    if(qrm->size() < 1 )
    {
        QMessageBox::warning(NULL, "注意", " com_dict_com 表找不到 MINFEE 类型值！");
        ui->tab_4->setEnabled(false);
    }
    else
    {
        while(qrm->next())
        {
            sql_str += qrm->value(0).toString() + " varchar(30) , ";
        }
    }
    if(!sql_str.isEmpty())
    {
        //医师收入临时表
        sq = "create temporary table if not exists tmp_feedetail "
             "("
             "doct_code varchar(20), "
             "doct_name varchar(20), "
             "dept_code varchar(20), "
             "dept_name varchar(20), "
             "起始时间 varchar(30), "
             "截止时间 varchar(30),";
        sq += sql_str + " 合计 varchar(30), ord int auto_increment PRIMARY key)";

        qDebug()<<"医师收入临时表 : " << sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::warning(NULL, "注意", " tmp_feedetail 创建表失败！");
            qDebug()<<sq;
            ui->tab_4->setEnabled(false);
        }

    }

    ui->pbPrintCount->setEnabled(false);

    //提取开诊科室列表
    sq = "select dept_name, dept_code from com_department where valid_state = '1' and regdept_flag = '1'";
    qDebug()<<"提取开诊诊室："<<sq;
    ui->cbb_dept_fee_detail->clear();
    ui->cbb_dept_fee_detail->addItem("全部");
    dept_code_rela = pub::fillCombo(ui->cbb_dept_fee_detail, sq , 0, qrot, false);
    dept_code_rela = "全部^^" + dept_code_rela;

    sq = "select name,code from com_dictionary where  type ='MINFEE' and valid_state = '1' ";
    qDebug()<<"提取费用类别："<<sq;
    ui->cbb_fee_type->clear();
    ui->cbb_fee_type->addItem("全部");
    fee_code_rela = pub::fillCombo(ui->cbb_fee_type, sq , 0, qrot,false);//
    fee_code_rela = "全部^^" + fee_code_rela;

    ui->cbb_doct_fee_detail->clear();
    ui->cbb_doct_fee_detail->addItem("全部");
    doct_code_rela = "全部^^" ;

    dlg_get_date = new pub_pop_get_date();
    dlg_delay = new Pub_pop_delay();

    ui->dte_begin->setDate(QDate::currentDate());
    ui->dte_end->setDate(QDate::currentDate());

    //ui->dte_begin->setDateTime(QDateTime::currentDateTime());
    ui->dte_begin->setDate(QDate::currentDate());
    ui->dte_begin->setTime(QTime::fromString("06:00:00", "HH:mm:ss"));

    //ui->dte_end->setDateTime(QDateTime::currentDateTime());
    ui->dte_end->setDate(QDate::currentDate());
    ui->dte_end->setTime(QTime::fromString("20:00:00", "HH:mm:ss"));

    md_fee_detail = new QSqlQueryModel();

    initial_finished = true;
    sql_for_print = "";

}

Form_gzltj::~Form_gzltj()
{
    delete ui;
}

void Form_gzltj::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/gzltj", QVariant(this->geometry()));

    emit destroyW( "gzltj" );
}

void Form_gzltj::on_pbExit_clicked()
{

    this->close();
}

void Form_gzltj::on_pbRun_clicked()
{
    //ui->pbRun->setEnabled(false);
    qApp->processEvents();  //刷新界面显示
    ui->leZcgh->setText("0");
    ui->leGhtf->setText("0");
    ui->leZcsf->setText("0");
    ui->leSftf->setText("0");
    ui->leHjje->setText("0");
    ui->leJjzf->setText("0");
    ui->leYbzh->setText("0");
    ui->leXjzf->setText("0");
    QString t;
    if(ui->rbWrj->isChecked()){
        t = " and ( balance_flag = '0' or balance_flag is null )";
    }else{
        if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
        {
            QMessageBox::information(this,"注意","指定的时间范围无效！");
            return;
        }
        QString operConfine;
        //无财务权限，一次最多查询7天本人数据
        if(ui->dte_end->dateTime() > ui->dte_begin->dateTime().addDays(7))
        {
            QMessageBox::information(this,"注意","指定的时间范围超限，单次查询最大范围一周！");
            return;
        }

        QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
        QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

        t = " and oper_date>=to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
        t += " and oper_date<=to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    }

    sq = "select '挂号' 类别 , invoice_no 发票号, decode ( trans_type,'1', '正', '2', '负' ) 状态, card_no 病志号,name 姓名,"
         " pact_name 收费方式,reg_fee+chck_fee+diag_fee+oth_fee 金额,"
         " pub_cost 基金支付,pay_cost 账户支付,own_cost 现金支付,valid_flag 有效,to_number(invoice_no) inv"
         " from fin_opr_register where oper_code= '" + pub::usr_code + "' " + t +
         " union"
         " select  '收费' 类别,invoice_no 发票号,decode  ( trans_type,'1', '正', '2', '负' ) 状态,card_no 病志号,name 姓名,"
         " pact_name 收费方式,tot_cost 金额,pub_cost 基金支付,pay_cost 账户支付,own_cost 现金支付,cancel_flag 有效,to_number(invoice_no) inv "
         " from fin_opb_invoiceinfo where oper_code= '" + pub::usr_code + "' " + t +
         " order by 类别, 状态 desc, 发票号";

    mdList.setQuery(sq, pub::db_o);


    if(mdList.record(0).value(0).toString().isEmpty()){
        QMessageBox::information(this,"注意","未找到指定范围的数据！");
        //ui->pbRun->setEnabled(true);
        ui->pbPrintOut->setEnabled(false);
        ui->pbBalance->setEnabled(false);
        return;
    }
    ui->pbPrintOut->setEnabled(true);
    //if(ui->rbWrj->isChecked())
//    {
        qrot->prepare(sq);//待后续计算用
        ui->pbBalance->setEnabled(false);
//    }
    //else
//    {
//        ui->pbPrintOut->setEnabled(false);
//        ui->pbBalance->setEnabled(false);
//    }
    double width = ui->tvItemList->width() - 50;
    ui->tvItemList->setModel(&mdList);

    pub::setColumnWidth(ui->tvItemList, "0.06^0.18^0.06^0.12^0.12^0.1^0.08^0.08^0.08^0.08", width);

    sq = "select count(distinct invoice_no) ,trans_type ,'r' from fin_opr_register "
         " where oper_code= '" + pub::usr_code + "' " + t + "  group by trans_type, 'r'"
         " union "
         " select count(distinct invoice_no) ,trans_type ,'f' from fin_opb_invoiceinfo "
         " where oper_code= '" + pub::usr_code + "' " + t + " group by trans_type, 'r'";
    if(!qro->exec(sq)){
        QMessageBox::warning(this,"注意","计算发票数量出现错误！");
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        //ui->pbRun->setEnabled(true);
        return;
    }

    while(qro->next()){
        if(qro->value(1).toString() == "1" && qro->value(2).toString() == "r"){
            ui->leZcgh->setText(qro->value(0).toString());
        }
        if(qro->value(1).toString() == "1" && qro->value(2).toString() == "f"){
            ui->leZcsf->setText(qro->value(0).toString());
        }

        if(qro->value(1).toString() == "2" && qro->value(2).toString() == "r"){
            ui->leGhtf->setText(qro->value(0).toString());
        }
        if(qro->value(1).toString() == "2" && qro->value(2).toString() == "f"){
            ui->leSftf->setText(qro->value(0).toString());
        }

    }

    sq = "select sum(reg_fee+chck_fee+diag_fee+oth_fee),sum(pub_cost),sum(pay_cost),sum(own_cost) from fin_opr_register "
         " where oper_code= '" + pub::usr_code + "' " + t +
         "  union "
         "select sum(tot_cost),sum(pub_cost),sum(pay_cost),sum(own_cost) from fin_opb_invoiceinfo "
         " where oper_code= '" + pub::usr_code + "' " + t ;
    if(!qro->exec(sq)){
        QMessageBox::warning(this,"注意","计算金额合计出现错误！");
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        //ui->pbRun->setEnabled(true);
        return;
    }
    //合计，基金，账户，现金
    double hj, jj, zh, xj;
    hj = 0;
    jj = 0;
    zh = 0;
    xj = 0;

    while(qro->next()){
        hj = hj + qro->value(0).toDouble();
        jj = jj + qro->value(1).toDouble();
        zh = zh + qro->value(2).toDouble();
        xj = xj + qro->value(3).toDouble();
    }

    ui->leHjje->setText(QString::asprintf("%.2f",hj));
    ui->leJjzf->setText(QString::asprintf("%.2f",jj));
    ui->leYbzh->setText(QString::asprintf("%.2f",zh));
    ui->leXjzf->setText(QString::asprintf("%.2f",xj));

    //ui->pbRun->setEnabled(true);
}

void Form_gzltj::on_pbPrintOut_clicked()
{

    jatg = QJsonArray();  //临时数据-挂号
    jats = QJsonArray();  //临时数据-收费

    QJsonArray jaa,*jat; //全部数据，分页数据, 临时数据-挂号/收费，
    QJsonObject jo, jot;//单元格，临时明细行
    QJsonDocument d;

    //检索起止时间
    if(ui->rbWrj->isChecked())
    {
        sq = "select max(end_date),'g' from fin_opr_daybalance where oper_code = '" + pub::usr_code + "' ";
        sq += " union select max(end_date),'s' from fin_opb_daybalance where oper_code = '" + pub::usr_code + "'";
        qro->exec(sq);
        while(qro->next())
        {
            if(qro->value(1).toString() == "g"){
                dt1g = qro->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss");
                if(dt1g.trimmed().isEmpty()){
                    dt1g = "2000-01-01 00:00:00";
                }
            }else{
                dt1s = qro->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss");
                if(dt1s.trimmed().isEmpty()){
                    dt1s = "2000-01-01 00:00:00";
                }
            }
        }
        //取服务器时间。本地时间经常与服务器时间不一致，会引起时间段错误。
        qro->exec("select sysdate from dual ");
        qro->next();
        dt2 =  qro->value(0).toDateTime().toString("yyyy-MM-dd HH:mm:ss");
    }
    else
    {
        dt1g = dt1s  = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
        dt2 = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    }


    ghtf = "";  //挂号退费明细，收款退费明细
    sktf = "";
    QString sjh,sjh0;    //收据号，前一收据号
    QString type, status;   //号段的类型，状态
    double zh, tc, xj, hj;  //账户，统筹，现金， 合计

    int sjzs,sjhn; //收据张数,收据号数值，前一收据号数值,挂号号段累计，收款号段累计
    sjzs = 0;

    zh = tc = xj = hj = 0;
    sjhn = -1;

    bool xhjs = false;//循环结束标志
    bool last_negtive = false;//最后一行数据是否为负

    qrot->exec();

    while(true)
    {

        if(!qrot->next())    //循环结束？
        {
            xhjs = true;
        }

        sjzs++;
        sjhn++;

        if( xhjs || sjhn != qrot->value("inv").toInt())//数据遍历结束，或收据号不连续
        {
            if(sjhn == 0)   //首次进入循环
            {
                sjh = qrot->value(1).toString();
                sjzs = 0;
            }
            else if(last_negtive && qrot->value(2).toString() == "负")//连续负号
            {

            }
            else
            {
                type == "挂号" ? jat = &jatg : jat = &jats;

                jot.insert("status", status); //状态
                jot.insert("sjh", sjh + (status == "负" ? "..." : " - ") + sjh0); //号段
                jot.insert("hd0", sjh);//号段起
                jot.insert("hd1", sjh0);//号段止
                jot.insert("zs", QString::number(sjzs));//张数
                jot.insert("xj", QString::asprintf("%.2f", xj));//现金
                jot.insert("zh", QString::asprintf("%.2f", zh));//账户
                jot.insert("tc", QString::asprintf("%.2f", tc));//统筹
                jot.insert("hj", QString::asprintf("%.2f", hj));//合计

                //开始新号段
                sjzs = 0;
                sjh = qrot->value(1).toString();
                xj = zh = tc = hj = 0;
                *jat << jot;
            }

        }
        xj += qrot->value(9).toDouble();
        zh += qrot->value(8).toDouble();
        tc += qrot->value(7).toDouble();
        hj += qrot->value(6).toDouble();

        if(xhjs) break ; //循环结束

        sjh0 = qrot->value(1).toString();
        sjhn = qrot->value("inv").toInt() ;
        type = qrot->value(0).toString(); //当前行类别，挂号或收款
        status = qrot->value(2).toString(); //正或负

        if(status == "负")
        {
            last_negtive =true;

            if(type == "挂号")
            {
                if(ghtf.isEmpty())
                {
                    ghtf = qrot->value(1).toString();
                }else{
                    ghtf += ", " + qrot->value(1).toString();
                }
            }else{
                if(sktf.isEmpty())
                {
                    sktf = qrot->value(1).toString();
                }else{
                    sktf += ", " + qrot->value(1).toString();
                }
            }
        }else{
            last_negtive =false;
        }
    }

    //构造分页打印数据，挂号

    preparePrintData(jaa, jatg, dt1g, "门诊挂号", ghtf );

    preparePrintData(jaa, jats, dt1s, "处方收费", sktf );

    printOutDirect(jaa);

    if(ui->rbWrj->isChecked())
    {
        ui->pbBalance->setEnabled(true);
    }

}

void Form_gzltj::printOutExcel(QJsonArray jsar)
{
    //api 函数原型
    typedef BOOL __stdcall (*pGetDefaultPrinter)(LPTSTR , LPDWORD);//
    typedef BOOL __stdcall (*pSetDefaultPrinter)(LPTSTR);//
    pGetDefaultPrinter getPrinterName = NULL;
    pSetDefaultPrinter setPrinterName = NULL;

    bool err = true;    //api 函数有效性标志
    QLibrary lib;
    QFile f;
    QString dllFile = pub::base_path;
    dllFile.append("/winspool.dll");

    if(f.exists(dllFile) ){ //态库存在且允许使用
        lib.setFileName("winspool");
        if(lib.load())
        {
            getPrinterName  = (pGetDefaultPrinter)lib.resolve("GetDefaultPrinterA");//
            setPrinterName = (pSetDefaultPrinter)lib.resolve("SetDefaultPrinterA") ;//

            if(getPrinterName != NULL && setPrinterName != NULL)
            {
                err = false;
            }
        }
    }

    QSettings setIni("clin.ini", QSettings::IniFormat);
    QString newPrName = setIni.value("sk/printer").toString();    //收款打印机名称
    QString curPrName;

    if(err)
    {
        QMessageBox::information(NULL, "注意","winspool.dll 无效，将使用系统默认打印机输出！");
    }
    else
    {
        char prtName[256];
        DWORD sz = 256;
        if(!getPrinterName((LPTSTR)prtName, (LPDWORD)&sz))
        {
            QMessageBox::information(NULL, "注意","无法获取系统当前打印机名称！");
        }
        curPrName = QString(prtName);

        if(!setPrinterName((LPTSTR)newPrName.toLatin1().data()))
        {
            QMessageBox::information(NULL, "注意","无法修改系统当前打印机！");
        }
    }

    QString fileName = pub::base_path;
    fileName.append("/sheets/shoufeirijie.xls");

    QFile fl(fileName);
    if(!fl.exists())
    {
        QMessageBox::information(this,"注意","日结算报表模板文件不存在！");
        return;
    }

    QAxObject *excel;   //操作excel用于打印输出
    excel = new QAxObject("Excel.Application"); //

    if(excel->isNull())
    {

            excel = new QAxObject("Ket.Application"); //

        if(excel->isNull())
        {
            QMessageBox::information(this,"错误","电子表启动失败！");
            return;
        }
    }


    QAxObject *wkBooks = excel->querySubObject("Workbooks");
    wkBooks->dynamicCall("Open(const QString&)", fileName);
    //QAxObject *book =  wkBooks->querySubObject("Open(const QString&)", fileName);
    QAxObject *book =  excel->querySubObject("ActiveWorkBook");
    QAxObject *wkSheets = book->querySubObject("WorkSheets");
    QAxObject *sheet = wkSheets->querySubObject("Item(int)", 1);
    QAxObject *cell  ;//= new QAxObject ;

    for(int i = 0; i < jsar.size(); i++)
    {
        //清空表格
        int row , col;
        for(row = 6; row < 14; row ++)
        {
            for(col = 3; col < 10; col++)
            {
                cell = sheet->querySubObject("Cells(int, int)", row, col);
                cell->setProperty("Value", "");
            }
        }

        cell = sheet->querySubObject("Cells(int, int)", 15, 3);//备注内容
        cell->setProperty("Value", "");

        QJsonArray ja = jsar[i].toArray();
        for(int j = 0; j< ja.size(); j++)
        {
            QJsonObject jo = ja[j].toObject();
            cell = sheet->querySubObject("Cells(int, int)", jo["row"].toInt(), jo["col"].toInt());//
            cell->setProperty("Value", jo["val"].toString());
        }

        book->dynamicCall("PrintOut()");   //打印输出
    }



    book->dynamicCall("Close(Boolean)", false);  // 关闭文件
    excel->dynamicCall("Quit()"); // 关闭excel
    delete excel;
    if(setPrinterName != NULL && !setPrinterName((LPTSTR)curPrName.toLatin1().data()))
    {
        QMessageBox::information(NULL, "注意","系统当前打印机已变更，请手动改回！");
    }

    //QMessageBox::information(this,"注意","打印输出完毕！");

}

void Form_gzltj::writeCell(int row, int col, QString val, QString item_name, QJsonArray &ja)
{
    QJsonObject jo;
    if(val != "0.00" )
    {
        jo.insert("row", row);
        jo.insert("col", col);
        jo.insert("val", val);//
        jo.insert("item_name", item_name);
        ja << jo;
    }
}

void Form_gzltj::on_pbBalance_clicked()
{
    ui->pbBalance->setEnabled(false);
    ui->pbPrintOut->setEnabled(false);
    //挂号

    qDebug()<<"jatg.size()"<<QString::number(jatg.size());
    if(jatg.size()>0)   //存在挂号数据
    {
        qro->exec("select seq_fin_regbalance.nextval from dual");
        qro->next();
        QString bal_no = qro->value(0).toString();

        sq = "update fin_opr_register set balance_no = '" + bal_no + "', balance_flag = '1', ";
        sq += " balance_date = sysdate, balance_opcd = '" + pub::usr_code + "'";
        sq += " where oper_code= '" + pub::usr_code + "' ";
        sq += " and oper_date >= to_date('" + dt1g + "','yyyy-mm-dd hh24:mi:ss') ";
        sq += " and oper_date <= to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss') ";
        qro->exec(sq);
        qDebug()<<sq;
        QString ivc_z;
        int tot_qty = 0;
        double tot_dig,tot_own,tot_pay,tot_pub;
        tot_dig = tot_own = tot_pay = tot_pub = 0;
        int seq = 0;
        for (int i = 0; i< jatg.size(); i++)
        {

            seq = i;    //出循环后，插入负数记录时需要
            sq = "insert into fin_opr_daybalancedetail(balance_no, order_no, begin_no,end_no,qty,";
            sq += " reg_fee,chk_fee,dig_fee,oth_fee,own_cost,pay_cost,pub_cost,valid_flag,oper_date)";
            sq += " values(";
            sq += "'" + bal_no + "'," + QString::number(i) + ",'";
            sq += jatg[i].toObject().value("hd0").toString() + "','";
            sq += jatg[i].toObject().value("hd1").toString() + "',";
            sq += jatg[i].toObject().value("zs").toString() + ",0,0,";
            sq += jatg[i].toObject().value("hj").toString() + ",0,";
            sq += jatg[i].toObject().value("xj").toString() + ",";
            sq += jatg[i].toObject().value("zh").toString() + ",";
            sq += jatg[i].toObject().value("tc").toString() + ",";
            QString vld;
            if(jatg[i].toObject().value("status").toString() != "负"){
                sq += "'1',to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss')";
                qro->exec(sq);
                qDebug()<<sq;
            }

            tot_qty += jatg[i].toObject().value("zs").toString().toInt();
            tot_dig += jatg[i].toObject().value("hj").toString().toDouble();
            tot_own += jatg[i].toObject().value("xj").toString().toDouble();
            tot_pay += jatg[i].toObject().value("zh").toString().toDouble();
            tot_pub += jatg[i].toObject().value("tc").toString().toDouble();
            if(jatg[i].toObject().value("status").toString() != "负")
            {
                ivc_z += jatg[i].toObject().value("sjh").toString() + ";";
            }
        }

        if(!ghtf.isEmpty())
        {
            //存在退费数据
            ivc_z += ghtf;

            QStringList tf = ghtf.split(", ");
            foreach(QString s , tf){
                sq = "select diag_fee,own_cost,pay_cost,pub_cost from fin_opr_register where trans_type = '2' and invoice_no = '" + s + "'";
                qro->exec(sq);
                qro->next();
                qDebug()<<sq;
                sq = "insert into fin_opr_daybalancedetail(balance_no, order_no, begin_no,end_no,qty,";
                sq += " reg_fee,chk_fee,dig_fee,oth_fee,own_cost,pay_cost,pub_cost,valid_flag,oper_date)";
                sq += " values(";
                sq += "'" + bal_no + "'," + QString::number(seq++) + ",'" + s + "','" + s + "',1,0,0,";
                sq += qro->value(0).toString()+",0," + qro->value(1).toString()+",";
                sq += qro->value(2).toString()+"," + qro->value(3).toString()+",'0',to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss')";
                qro->exec(sq);
                qDebug()<<sq;
            }

        }

        sq = "insert into fin_opr_daybalance(invoice_zone,check_flag,oper_date,oper_code,balance_no,";
        sq += " begin_date,end_date,tot_qty,tot_reg,tot_chk,tot_dig,tot_oth,tot_own,tot_pay,tot_pub)";
        sq += " values('"+ivc_z+"','0',to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'),'"+pub::usr_code+"','"+bal_no+"',";
        sq += " to_date('" + dt1g + "','yyyy-mm-dd hh24:mi:ss'),to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss')";
        sq += "," + QString::number(tot_qty) + ",0,0," + QString::number(tot_dig) + ",0,";
        sq += QString::number(tot_own) + "," + QString::number(tot_pay) + "," + QString::number(tot_pub)+")" ;
        qDebug()<<sq;
        qro->exec(sq);

    }

    //收费
    qDebug()<<"jats.size()"<<QString::number(jats.size());

    if(jats.size()>0)   //存在收费数据
    {
        qro->exec("select SEQ_FIN_DAYBALANCE.nextval from dual");
        qro->next();
        QString bal_no = qro->value(0).toString();

        //按收费类别统计
        sq = "select t.invo_code, max(t.invo_name) as invo_name, sum(nvl(t.pub_cost,0))+sum(nvl(t.pay_cost,0))+sum(nvl(t.own_cost,0)) as money";
        sq += " from fin_opb_invoicedetail t where t.oper_code='" + pub::usr_code + "' ";
        sq += " and t.oper_date>=to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss')";
        sq += " and t.oper_date<=to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')";
        sq += " and BALANCE_FLAG='0' group by t.invo_code";
        qDebug()<<sq;
        if(!qro->exec(sq))
        {
             QMessageBox::information(this,"注意","按收费类别统计提取数据发生错误！");

             return;
        }

        while(qro->next())
        {
            sq = "insert into fin_opb_daybalance" ;
            sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                  "invoice_no,extent_field1,balance_item,sort_id)";
            sq += " values ";
            sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
            sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + qro->value(2).toString();
            sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
            sq += "'" + qro->value(0).toString() + "','" + qro->value(1).toString() +"','4','TOT_COST')";
            qDebug()<<sq;
            if(!qrot->exec(sq))
            {
                 QMessageBox::information(this,"注意","保存按收费类别统计数据发生错误！");

                 return;
            }

        }
        sq = "update fin_opb_invoicedetail set balance_no = '" + bal_no + "', balance_flag = '1', ";
        sq += " balance_date = sysdate, balance_opcd = '" + pub::usr_code + "'";
        sq += " where oper_code= '" + pub::usr_code + "' ";
        sq += " and oper_date >= to_date('" + dt1s + "','yyyy-mm-dd hh24:mi:ss') ";
        sq += " and oper_date <= to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss') ";
        qDebug()<<sq;

        if(!qro->exec(sq))
        {
             QMessageBox::information(this,"注意","保存收费明细数据表日结过程发生错误！");
             return;
        }


        //按收费方式统计
        sq = "select sum(nvl(a.own_cost,0)) , sum(nvl(a.pay_cost,0)) ,sum(nvl(a.pub_cost,0)) from fin_opb_invoiceinfo a";
        sq += " where a.oper_code='"+pub::usr_code +"' and a.oper_date>to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss') ";
        sq += " and a.oper_date<=to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss') and BALANCE_FLAG='0'";
        qDebug()<<sq;
        if(!qro->exec(sq))
        {
             QMessageBox::information(this,"注意","按收费方式提取数据发生错误！");
             return;
        }
        if(qro->next())
        {
            sq = "insert into fin_opb_daybalance" ;
            sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                  "invoice_no,extent_field1,balance_item,sort_id)";
            sq += " values ";
            sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
            sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + qro->value(0).toString();
            sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
            sq += "'A023','上缴现金','6','A023|TOT_COST')";
            qDebug()<<sq;
            if(!qrot->exec(sq))
            {
                 QMessageBox::information(this,"注意","保存上缴现金数据发生错误！");
                 return;
            }


            sq = "insert into fin_opb_daybalance" ;
            sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                  "invoice_no,extent_field1,balance_item,sort_id)";
            sq += " values ";
            sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
            sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + qro->value(1).toString();
            sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
            sq += "'A015','账户支付','6','A015|TOT_COST')";
            qDebug()<<sq;
            if(!qrot->exec(sq))
            {
                 QMessageBox::information(this,"注意","保存账户支付数据发生错误！");
                 return;
            }


            sq = "insert into fin_opb_daybalance" ;
            sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                  "invoice_no,extent_field1,balance_item,sort_id)";
            sq += " values ";
            sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
            sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + qro->value(2).toString();
            sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
            sq += "'A016','市保统筹','6','A016|TOT_COST')";
            qDebug()<<sq;
            if(!qrot->exec(sq))
            {
                 QMessageBox::information(this,"注意","保存统筹支付数据发生错误！");
                 return;
            }

        }

        sq = "update fin_opb_invoiceinfo set balance_no = '" + bal_no + "', balance_flag = '1', ";
        sq += " balance_date = sysdate, balance_opcd = '" + pub::usr_code + "'";
        sq += " where oper_code= '" + pub::usr_code + "' ";
        sq += " and oper_date >= to_date('" + dt1s + "','yyyy-mm-dd hh24:mi:ss') ";
        sq += " and oper_date <= to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss') ";
        qDebug()<<sq;

        if(!qrot->exec(sq))
        {
             QMessageBox::information(this,"注意","保存收费信息表日结数据发生错误！");
             return;
        }

        int tot_qty0 = 0;   //正数张数
        int tot_qty1 = 0;   //负数张数
        double tot_hj1 = 0;  //负数金额

        for (int i = 0; i< jats.size(); i++)
        {
            if(jats[i].toObject().value("status").toString() == "负")
            {
                //一次结算，负号段只可能有一个
                tot_qty1 = jats[i].toObject().value("zs").toString().toInt();
                tot_hj1 = 0 - jats[i].toObject().value("hj").toString().toDouble();

                sq = "insert into fin_opb_daybalance" ;
                sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                      "invoice_no,extent_field1,balance_item,sort_id,EXTENT_FIELD5)";
                sq += " values ";
                sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
                sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + QString::number(tot_qty1);
                sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
                sq += "'A004','退费票据','5','A00401|TOT_COST、A00402|EXTENT_FIELD5','" + sktf + "')";
                qDebug()<<sq;
                if(!qrot->exec(sq))
                {
                     QMessageBox::information(this,"注意","保存退费票据张数数据发生错误！");
                     return;
                }

                sq = "insert into fin_opb_daybalance" ;
                sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                      "invoice_no,extent_field1,balance_item,sort_id)";
                sq += " values ";
                sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
                sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + QString::number(tot_hj1);
                sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
                sq += "'A006','退费金额','5','A006|TOT_COST')";
                qDebug()<<sq;
                if(!qrot->exec(sq))
                {
                     QMessageBox::information(this,"注意","保存退费金额数据发生错误！");
                     return;
                }

            }
            else
            {
                //正数票据张数累计
                tot_qty0 += jats[i].toObject().value("zs").toString().toInt();

                //保存正数号段
                sq = "insert into fin_opb_daybalance" ;
                sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
                      "invoice_no,extent_field1,balance_item,sort_id,extent_field2)";
                sq += " values ";
                sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
                sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss'),0";
                sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
                sq += "'A001-"+QString::number(i)+"','起止票据号','5','A00101|EXTENT_FIELD2、A00102|EXTENT_FIELD3','";
                sq += jats[i].toObject().value("sjh").toString() + "')";
                qDebug()<<sq;
                if(!qrot->exec(sq))
                {
                     QMessageBox::information(this,"注意","保存号段数据发生错误！");
                     return;
                }

            }
        }

        sq = "insert into fin_opb_daybalance" ;
        sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
              "invoice_no,extent_field1,balance_item,sort_id)";
        sq += " values ";
        sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
        sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + QString::number(tot_qty0 + tot_qty1);
        sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
        sq += "'A002','票据总数','5','A002|TOT_COST')";
        qDebug()<<sq;
        if(!qrot->exec(sq))
        {
             QMessageBox::information(this,"注意","保存票据总数数据发生错误！");
             return;
        }
        sq = "insert into fin_opb_daybalance" ;
        sq += " (blance_no,begin_date,end_date,tot_cost,oper_code,oper_name,oper_date,"
              "invoice_no,extent_field1,balance_item,sort_id)";
        sq += " values ";
        sq += " ('" + bal_no + "', to_date('" + dt1s + "','yyyy-MM-dd hh24:mi:ss'),";
        sq += "to_date('" + dt2 + "','yyyy-MM-dd hh24:mi:ss')," + QString::number(tot_qty0 );
        sq += ",'" + pub::usr_code + "','" + pub::usr_name + "', to_date('" + dt2 + "','yyyy-mm-dd hh24:mi:ss'), ";
        sq += "'A003','有效票据','5','A003|TOT_COST')";
        qDebug()<<sq;
        if(!qrot->exec(sq))
        {
             QMessageBox::information(this,"注意","保存有效票据张数数据发生错误！");
             return;
        }

    }

    QMessageBox::information(this,"注意","结账信息保存完毕！");

}

void Form_gzltj::printOutDirect(QJsonArray jsar)
{
    for(int i = 0; i < jsar.size(); i++)
    {
        pnt->begin(prt);
        printPageBase();

        QJsonArray ja = jsar[i].toArray();
        for(int j = 0; j < ja.size(); j++)
        {
            QJsonObject jo = ja[j].toObject();

            qrmp->exec("select p_font_size , p_position , p_font_name from com_printer_setting where p_item_type = 'item' "
                       " and p_type = '收费日结' and p_item = '"+jo["item_name"].toString()+"'");
            qrmp->next();
            QFont ft;
            ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
            ft.setFamily(qrmp->value("p_font_name").toString());
            pnt->setFont(ft);

            int flag;
            if(qrmp->value("p_position").toInt() == 0){ //左
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
            }else if(qrmp->value("p_position").toInt() == 1){//中
                flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
            }else{          //右
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
            }

            QRectF f = getRealPosition(jo["row"].toInt(), jo["col"].toInt());
            pnt->drawText(f, flag, jo["val"].toString(), NULL);

        }
        pnt->end();

    }

}

void Form_gzltj::printPageBase()
{

    //表格线
    double x1, y1, x2, y2, width ;
    QPen p ;
    p.setStyle(Qt::SolidLine);

    sq = "select p_type,p_item,p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
         "p_position,p_mode,p_print_item,p_item_type from com_printer_setting "
         "where p_type = '收费日结' and p_item_type = 'base'";
    qrmp->exec(sq);
    while(qrmp->next())
    {

        if( qrmp->value("p_item") == "line")
        {
        width = qrmp->value("p_font_size").toDouble();
        y1 = (qrmp->value("p_top").toDouble() + yPos) * ptScale;
        x1 = (qrmp->value("p_left").toDouble() + xPos) * ptScale;
        y2 = (qrmp->value("p_width").toDouble() + yPos) * ptScale;
        x2 = (qrmp->value("p_height").toDouble() + xPos) * ptScale;

        p.setWidth( ptScale * width);
        pnt->setPen(p);
        pnt->drawLine(x1, y1, x2, y2);

        }
        else if( qrmp->value("p_item") == "固定内容")
        {
            QFont ft;
            ft.setPixelSize(int(ptScale * qrmp->value("p_font_size").toDouble()));
            ft.setFamily(qrmp->value("p_font_name").toString());
            pnt->setFont(ft);

            int flag;
            if(qrmp->value("p_position").toInt() == 0){ //左
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft ;
            }else if(qrmp->value("p_position").toInt() == 1){//中
                flag = Qt::AlignCenter ;//Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignHCenter
            }else{          //右
                flag = Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignRight ;
            }

            QString txt = qrmp->value("p_print_item").toString();
            QRectF f = getRealPosition(qrmp->value("p_top").toInt(), qrmp->value("p_left").toInt());
            pnt->drawText(f, flag, txt, NULL);
        }
    }
}

QRectF Form_gzltj::getRealPosition(int row, int col)
{
    sq = "select p_item,p_top,p_left,p_width,p_height from com_printer_setting"
         " where p_item in ('行','列') ";
    sq += " and p_top in(" + QString::number(row) + "," + QString::number(col) + ")";
    float x1,x2,y1,y2;
    x1 = x2 = y1 = y2 = 0;
    qrm->exec(sq);

    while(qrm->next())
    {

        if(qrm->value("p_item").toString() == "行" && qrm->value("p_top").toInt() == row)
        {
            y1 = (qrm->value("p_width").toDouble() + yPos) * ptScale;
            y2 = (qrm->value("p_height").toDouble() + yPos) * ptScale;
        }
        if(qrm->value("p_item").toString() == "列" && qrm->value("p_top").toInt() == col)
        {
            x1 = (qrm->value("p_width").toDouble() + margin + xPos) * ptScale;
            x2 = (qrm->value("p_height").toDouble() - margin + xPos) * ptScale;
        }
    }

    QPointF p1 = QPointF(x1, y1);
    QPointF p2 = QPointF(x2, y2);
    return QRectF(p1 , p2);

}

void Form_gzltj::preparePrintData(QJsonArray &jaa, QJsonArray &jat, QString dt1, QString title, QString tf )
{
    //构造分页打印数据
    QJsonArray jap;
    QJsonObject jot;

    int lines = jat.size();//行数
    if(lines < 1 )
    {
        //无有效数据
        return;
    }

    int pages = lines / MAX_LINES_BILL; //共页

    if(lines % MAX_LINES_BILL > 0)
    {
        pages += 1;
    }

    int page = 1;//第页
    int line;//行

    for(int i = 0; i < pages ; i++) //页
    {

        writeCell( 2, 29, "（" + title + "）日结清单", "日结清单", jap);//标题
        writeCell( 3, 29, "票据日期：" + dt1 + " - " + dt2, "票据日期", jap);//票据日期范围
        writeCell( 17, 29, "收费员：" + pub::usr_name, "收费员", jap);//收费员
        writeCell( 17, 69, QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"), "打印日期", jap);//打印日期
        writeCell( 3, 69, "第 " + QString::number(page) + " 页 / 共 " + QString::number(pages) + " 页", "页码", jap);
        QString memo;   //备注内容
        int zsz,zsf;
        double  xj,zh,tc,hj;
        zsz = zsf = 0;
        xj = zh = tc = hj = 0;

        for(int j = 0; j < MAX_LINES_BILL ; j++) //每页最多行数。
        {
            line = i * MAX_LINES_BILL + j;

            if(line < lines)    //挂号
            {
                jot = jat[line].toObject();//一行数据

                writeCell( j + 6, 3, jot["sjh"].toString(), "收费号段", jap);//收据号

                if(jot["status"].toString() == "正") //票据张数
                {
                    writeCell( j + 6, 4, jot["zs"].toString(), "收费正常张数", jap);//正常
                    zsz += jot["zs"].toString().toInt();
                }else{
                    writeCell( j + 6, 5, jot["zs"].toString(), "收费退费张数", jap);//退费
                    zsf += jot["zs"].toString().toInt();
                    //一次日结，每个类别只可能有一个退费段,不需要考虑多个备注连接问题。
                    memo = "挂号退费票据号：" + tf + "\n";
                }

                writeCell( j + 6, 6, jot["xj"].toString(), "收费现金", jap);//
                writeCell( j + 6, 7, jot["zh"].toString(), "收费账户", jap);//
                writeCell( j + 6, 8, jot["tc"].toString(), "收费统筹", jap);//
                writeCell( j + 6, 9, jot["hj"].toString(), "收费总额", jap);//

                xj += jot["xj"].toString().toDouble();
                hj += jot["hj"].toString().toDouble();
                zh += jot["zh"].toString().toDouble();
                tc += jot["tc"].toString().toDouble();
            }

        }

        if(!memo.isEmpty()) //本页有备注
        {
            writeCell( 15, 39, memo, "备注", jap);
        }

        writeCell( 14, 4, QString::number(zsz), "收费正常张数", jap);//正常
        writeCell( 14, 5, QString::number(zsf), "收费退费张数", jap);//退费
        writeCell( 14, 6, QString::asprintf("%.2f", xj), "收费现金", jap);//
        writeCell( 14, 7, QString::asprintf("%.2f", zh), "收费账户", jap);//
        writeCell( 14, 8, QString::asprintf("%.2f", tc), "收费统筹", jap);//
        writeCell( 14, 9, QString::asprintf("%.2f", hj), "收费总额", jap);//

        writeCell( 16, 3, QString::asprintf("%.2f",xj), "上缴现金", jap);//
        writeCell( 16, 69, pub::bigW(xj), "现金大写", jap);//

        jaa << jap;
        jap = QJsonArray();
        page ++;
    }

}

void Form_gzltj::on_tabWidget_currentChanged(int index)
{
    Q_UNUSED(index)
    ui->tvItemList->setModel(NULL);
    ui->tvDetail->setModel(NULL);
    ui->tvDetail_2->setModel(NULL);
}

void Form_gzltj::on_pbQuery_clicked()
{
    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }
    QString operConfine;
    if(!privFinance)
    {
        //无财务权限，一次最多查询7天本人数据
        if(ui->dte_end->dateTime() > ui->dte_begin->dateTime().addDays(7))
        {
            QMessageBox::information(this,"注意","指定的时间范围超限，单次查询最大范围一周！");
            return;
        }
        operConfine = " oper_code = '" + pub::usr_code + "' ";
    }
    else
    {
        if(ui->dte_end->dateTime() > ui->dte_begin->dateTime().addDays(93))
        {
            QMessageBox::information(this,"注意","指定的时间范围超限，单次查询最大范围三个月！");
            return;
        }
        if(ui->cbbOper_2->currentText() == "全部")
        {
            operConfine = " 1 = 1 ";
        }
        else
        {
            operConfine = " oper_code = '" + oper_code[ui->cbbOper_2->currentText()] + "' ";
        }
    }

    QString cond_cancel = "";
    if(ui->ckb_valid->isChecked() )
    {
        cond_cancel = " and cancel_opcd is null ";
    }

    if( !ui->ckb_cash->isChecked() && !ui->ckb_insu->isChecked())
    {
        QMessageBox::information(this,"注意","医保和现金至少要选择一项！");
        return;
    }

    QString cond_mode = " and pact_code in ('a'";

    if(ui->ckb_insu->isChecked() )
    {
        cond_mode += ", '2'";
    }

    if(ui->ckb_cash->isChecked() )
    {
        cond_mode += ", '1'";
    }

    cond_mode += ") ";

    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString dateRange = " and oper_date>=to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRange += " and oper_date<=to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    ui->pbQuery->setEnabled(false);
    qApp->processEvents();  //刷新界面显示
    ui->leYbf->setText("0");
    ui->leYbz->setText("0");
    ui->leXjf->setText("0");
    ui->leXjz->setText("0");
    ui->leHjje_2->setText("0");
    ui->leJjzf_2->setText("0");
    ui->leYbzh_2->setText("0");
    ui->leXjzf_2->setText("0");

    if(ui->rbGh->isChecked())
    {
        qDebug() << "查询挂号明细数据 ：" ;
        sq = "select oper_code 收费员, oper_date 时间, '挂号' 类别 , invoice_no 发票号, decode ( trans_type,'1', '正', '2', '负' ) 状态, card_no 病志号,name 姓名,"
                 " pact_name 收费方式,reg_fee+chck_fee+diag_fee+oth_fee 金额,"
                 " pub_cost 基金支付,pay_cost 账户支付,own_cost 现金支付,valid_flag 有效,to_number(invoice_no) inv"
                 " from fin_opr_register where "
                + operConfine + cond_cancel + cond_mode;
        sq += dateRange + " order by oper_date, 类别, 状态 desc, 发票号";
    }
    else if(ui->rbSf->isChecked())
    {
        qDebug() << "查询收费明细数据 ：" ;
        sq = " select  oper_code 收费员, oper_date 时间, '收费' 类别,invoice_no 发票号,decode  ( trans_type,'1', '正', '2', '负' ) 状态,card_no 病志号,name 姓名,"
             " pact_name 收费方式,tot_cost 金额,pub_cost 基金支付,pay_cost 账户支付,own_cost 现金支付,cancel_flag 有效,to_number(invoice_no) inv "
             " from fin_opb_invoiceinfo where "
                + operConfine + cond_cancel + cond_mode;
        sq += dateRange + " order by oper_date, 类别, 状态 desc, 发票号";
    }
    else if(ui->rb_un_doct_see->isChecked())
    {

        qDebug() << "查询挂号未就诊数据 ：" ;
        sq = "select oper_code 收费员, oper_date 时间, '挂号' 类别 , invoice_no 发票号, decode ( trans_type,'1', '正', '2', '负' ) 状态, card_no 病志号,name 姓名,"
                 " pact_name 收费方式,reg_fee+chck_fee+diag_fee+oth_fee 金额,"
                 " pub_cost 基金支付,pay_cost 账户支付,own_cost 现金支付,valid_flag 有效,to_number(invoice_no) inv"
                 " from fin_opr_register where see_docd is null and "
              + operConfine + cond_cancel + cond_mode;
        sq += dateRange + " order by oper_date, 类别, 状态 desc, 发票号";
    }
    else
    {
        QMessageBox::information(this,"注意","查询范围错误！");
        ui->pbQuery->setEnabled(true);
        return;
    }

    qDebug() << sq;
    mdList.setQuery(sq, pub::db_o);

    if(mdList.record(0).value(0).toString().isEmpty()){
        QMessageBox::information(this,"注意","未找到指定范围的数据！");
        ui->pbQuery->setEnabled(true);
        ui->pbPrintOut->setEnabled(false);
        ui->pbBalance->setEnabled(false);
        return;
    }

    if(ui->rbWrj->isChecked())
    {
        qrot->prepare(sq);//待后续计算用
        ui->pbPrintOut->setEnabled(true);
        ui->pbBalance->setEnabled(false);
    }
    else
    {
        ui->pbPrintOut->setEnabled(false);
        ui->pbBalance->setEnabled(false);
    }
    double width = ui->tvDetail->width() - 50;
    ui->tvDetail->setModel(&mdList);

    pub::setColumnWidth(ui->tvDetail, "0.06^0.12^0.06^0.12^0.06^0.10^0.10^0.1^0.06^0.06^0.06^0.06", width);

    if(ui->rbGh->isChecked())
    {
        sq = "select count(distinct invoice_no) ,trans_type, pact_code from fin_opr_register "
             " where  " + operConfine ;
        sq += dateRange + " group by trans_type, pact_code";
    }
    else
    {
        sq = "select count(distinct invoice_no) ,trans_type, pact_code from fin_opb_invoiceinfo "
                 " where " + operConfine;
        sq += dateRange + " group by trans_type, pact_code";
    }

    if(!qro->exec(sq)){
        QMessageBox::warning(this,"注意","计算发票数量出现错误！");
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        ui->pbQuery->setEnabled(true);
        return;
    }
    ui->leYbz->setText(""); //医保正数票据张数
    ui->leYbf->setText(""); //医保负数票据张数
    ui->leXjz->setText(""); //现金正数票据张数
    ui->leXjf->setText(""); //现金负数票据张数
    while(qro->next()){
        if(qro->value(1).toString() == "1" && qro->value(2).toString() == "1"  ){
            ui->leXjz->setText(qro->value(0).toString());
        }
        if(qro->value(1).toString() == "1" && qro->value(2).toString() == "2"  ){
            ui->leYbz->setText(qro->value(0).toString());
        }
        if(qro->value(1).toString() == "2" && qro->value(2).toString() == "1"  ){
            ui->leXjf->setText(qro->value(0).toString());
        }
        if(qro->value(1).toString() == "2" && qro->value(2).toString() == "2"  ){
            ui->leYbf->setText(qro->value(0).toString());
        }
    }

    if(ui->rbGh->isChecked())
    {
        sq = "select sum(reg_fee+chck_fee+diag_fee+oth_fee),sum(pub_cost),sum(pay_cost),sum(own_cost) from fin_opr_register "
             " where " + operConfine + dateRange ;
    }
    else
    {
        sq = "select sum(tot_cost),sum(pub_cost),sum(pay_cost),sum(own_cost) from fin_opb_invoiceinfo "
        " where " + operConfine + dateRange ;
    }

    if(!qro->exec(sq)){
        QMessageBox::warning(this,"注意","计算金额合计出现错误！");
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        ui->pbQuery->setEnabled(true);
        return;
    }
    //合计，基金，账户，现金
    double hj, jj, zh, xj;
    hj = 0;
    jj = 0;
    zh = 0;
    xj = 0;

    while(qro->next()){
        hj = hj + qro->value(0).toDouble();
        jj = jj + qro->value(1).toDouble();
        zh = zh + qro->value(2).toDouble();
        xj = xj + qro->value(3).toDouble();
    }

    ui->leHjje_2->setText(QString::asprintf("%.2f",hj));
    ui->leJjzf_2->setText(QString::asprintf("%.2f",jj));
    ui->leYbzh_2->setText(QString::asprintf("%.2f",zh));
    ui->leXjzf_2->setText(QString::asprintf("%.2f",xj));

    ui->pbQuery->setEnabled(true);
}

void Form_gzltj::on_pbQuery_2_clicked()
{
    if(ui->cbbOper->count() < 1)
    {
        QMessageBox::warning(NULL, "注意", "系统中找不到角色定义为‘收款员’的用户！");
        return;
    }

    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }



    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString dateRange = " and oper_date>=to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRange += " and oper_date<=to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    QString tmp ;
    if(ui->cbbOper->currentText() != "全部")
    {
        tmp = " and oper_code = '" + oper_code[ui->cbbOper->currentText()] + "' ";
    }else
    {
        tmp = "";
    }

    if(ui->rbGh_2->isChecked())
    {
        //clear last query value
        qrm->exec("delete from tmp_balance_opr");
        //insert all data
        sq = " select oper_code,TO_CHAR(begin_date,'yyyy-mm-dd hh24:mi:ss') 起始时间, TO_CHAR(end_date,'yyyy-mm-dd hh24:mi:ss') 截止时间,"
        " TO_CHAR(oper_date,'yyyy-mm-dd hh24:mi:ss') 日结时间, tot_qty 挂号人次 , tot_reg 挂号费, tot_chk 检查费, "
        " tot_dig 诊察费, tot_oth 其它, tot_own 现金, tot_pay 账户, tot_pub 统筹 from FIN_OPR_DAYBALANCE ";
        sq += " where 1 = 1 " + dateRange + tmp;
        sq += " order by oper_code, oper_date";
        qDebug()<<"select all data :"<<sq;
        qro->exec(sq);
        while(qro->next())
        {
            sq = "insert into tmp_balance_opr (操作员, 起始时间, 截止时间, 日结时间, 挂号人次, 挂号费, 检查费, 诊察费, 其它, 现金, 账户, 统筹)";
            sq += " values ('";
            sq += qro->value("oper_code").toString() + "','";
            sq += qro->value("起始时间").toString() + "','";
            sq += qro->value("截止时间").toString() + "','";
            sq += qro->value("日结时间").toString() + "',";
            sq += qro->value("挂号人次").toString() + ",'";
            sq += QString::asprintf("%.2f", qro->value("挂号费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("检查费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("诊察费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("其它").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("现金").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("账户").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("统筹").toDouble()) + "')";
            if(!qrm->exec(sq))
            {
                QMessageBox::information(this,"注意","插入 tmp_balance_opr 明细 发生错误！\n" + qrm->lastError().text());
                qDebug()<<"插入 tmp_balance_opr 发生错误！";
                qDebug()<< qrm->lastError().text();
                qDebug()<<sq;
                return;
            }
            //qDebug()<<"insert into tmp_table :"<<sq;
        }

        //inser sub_amount
        sq = " select oper_code, sum(tot_qty) 挂号人次 , sum(tot_reg) 挂号费, sum(tot_chk) 检查费, sum(tot_dig) 诊察费, "
             " sum(tot_oth) 其它, sum(tot_own) 现金, sum(tot_pay) 账户, sum(tot_pub) 统筹 from FIN_OPR_DAYBALANCE ";
        sq += " where 1 = 1 " + dateRange + tmp;
        sq += " group by oper_code order by oper_code ";
        qDebug()<<"select sub amount data : " << sq;
        qro->exec(sq);
        while(qro->next())
        {
            sq = "insert into tmp_balance_opr (操作员, 挂号人次, 挂号费, 检查费, 诊察费, 其它, 现金, 账户, 统筹)";
            sq += " values('";
            sq += qro->value("oper_code").toString() + "',";
            sq += qro->value("挂号人次").toString() + ",'";
            sq += QString::asprintf("%.2f", qro->value("挂号费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("检查费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("诊察费").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("其它").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("现金").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("账户").toDouble()) + "','";
            sq += QString::asprintf("%.2f", qro->value("统筹").toDouble()) + "')";
            if(!qrm->exec(sq))
            {
                QMessageBox::information(this,"注意","插入 tmp_balance_opr 合计 发生错误！\n" + qrm->lastError().text());
                qDebug()<<"插入 tmp_balance_opr 发生错误！";
                qDebug()<< qrm->lastError().text();
                qDebug()<<sq;
                return;
            }
            qDebug()<<"insert into tmp_table :"<<sq;
        }

        //change oper_code to oper_name
        sq = "select distinct 操作员 from tmp_balance_opr";
        qrm->exec(sq);
        while(qrm->next())
        {
            sq = "update tmp_balance_opr set 操作员 = (select empl_name from com_employee where empl_code = '"
                    + qrm->value(0).toString() + "' limit 1 ) ";
            sq += " where 操作员 = '"  + qrm->value(0).toString() + "'";
            qrmp->exec(sq);
            qDebug()<< "change oper_code to oper_name" << sq;
        }

        sq = "update tmp_balance_opr set 操作员 = concat(操作员, ' - 合计')"
             " where 起始时间 is null";
        qrm->exec(sq);
        qDebug()<< "change sub_amount oper_code to oper_name" << sq;

        //insert amount
        sq = " select sum(tot_qty) 挂号人次 , sum(tot_reg) 挂号费, sum(tot_chk) 检查费, sum(tot_dig) 诊察费, "
             " sum(tot_oth) 其它, sum(tot_own) 现金, sum(tot_pay) 账户, sum(tot_pub) 统筹 from FIN_OPR_DAYBALANCE ";
        sq += " where 1 = 1 " + dateRange + tmp;
        qro->exec(sq);
        qro->next();
        sq = "insert into tmp_balance_opr (操作员, 挂号人次,  挂号费,  检查费,  诊察费,  其它, 现金,  账户,  统筹)";
        sq += " values('总合计',";
        sq += qro->value("挂号人次").toString() + ",'";
        sq += QString::asprintf("%.2f", qro->value("挂号费").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("检查费").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("诊察费").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("其它").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("现金").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("账户").toDouble()) + "','";
        sq += QString::asprintf("%.2f", qro->value("统筹").toDouble()) + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","插入 tmp_balance_opr 汇总 发生错误！\n" + qrm->lastError().text());
            qDebug()<<"插入 tmp_balance_opr 发生错误！";
            qDebug()<< qrm->lastError().text();
            qDebug()<<sq;
            return;
        }
        qDebug()<<"insert into tmp_table :"<<sq;


        //remove invalid data
        //sq = "delete from tmp_balance_opr where 挂号人次 = ''";
        //qrm->exec(sq);

        sq = "select 操作员, 起始时间, 截止时间, 挂号人次 人次, 挂号费, 检查费, 诊察费, 其它, 现金, 账户, 统筹, ord"
             " from tmp_balance_opr order by ord"; // 日结时间,
        mdList.setQuery(sq, pub::db_m);

        if(mdList.rowCount()<1)
        {
            QMessageBox::information(this,"注意","指定的时间范围无数据！");
            ui->tvDetail_2->setModel(NULL);
        }
        else
        {
            ui->tvDetail_2->setModel(&mdList);
            int width = ui->tvDetail_2->width();
            pub::setColumnWidth(ui->tvDetail_2, "0.1^0.15^0.15^0.07^0.07^0.07^0.07^0.07^0.07^0.07^0.07", width);
        }

    }
    else
    {
        //收费
        //clear last query value
        qrm->exec("delete from tmp_balance_opb");
        //insert all data
        sq = " select blance_no, TO_CHAR(begin_date,'yyyy-mm-dd hh24:mi:ss') 起始时间, TO_CHAR(end_date,'yyyy-mm-dd hh24:mi:ss') 截止时间,"
             " oper_name,oper_code,invoice_no, tot_cost  from fin_opb_daybalance "
             " where invoice_no in('A015','A016','A023','A002') " + dateRange + tmp;
        sq += " order by oper_code, oper_date";
        qDebug()<<"select all data :"<<sq;
        qro->exec(sq);
        QString blcn = "";
        double amount = 0;
        bool first = true;      //首次进入循环
        QMap<QString,QString> val;
        while(qro->next())
        {
            if(blcn != qro->value("blance_no").toString() )
            {
                if(first)
                {
                    first = false;
                }
                else
                {
                    sq = "insert into tmp_balance_opb (操作员, 起始时间, 截止时间, 日结时间, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额)";
                    sq += " values ('";
                    sq += val["操作员"] + "','";
                    sq += val["起始时间"] + "','";
                    sq += val["截止时间"] + "','";
                    sq += val["日结时间"] + "','";
                    sq += val["票据张数"] + "','";
                    sq += QString::asprintf("%.2f", amount) + "','";
                    sq += val["现金金额"] + "','";
                    sq += val["账户金额"] + "','";
                    sq += val["统筹金额"] + "')";
                    if(!qrm->exec(sq))
                    {
                        QMessageBox::information(this,"注意","in cycle 插入 tmp_balance_opb 明细 发生错误！\n" + qrm->lastError().text());
                        qDebug()<<"插入 tmp_balance_opb 发生错误！";
                        qDebug()<< qrm->lastError().text();
                        qDebug()<<sq;
                        return;
                    }

                }
                val.clear();
                amount = 0;
                val["操作员"] = qro->value("oper_name").toString();
                val["起始时间"] = qro->value("起始时间").toString();
                val["截止时间"] = qro->value("截止时间").toString();
                val["日结时间"] = "";  //unused
                val["现金金额"] = "0";
                val["账户金额"] = "0";
                val["统筹金额"] = "0";
            }

            if(qro->value("invoice_no").toString() == "A015")
            {
                val["账户金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A016")
            {
                val["统筹金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A023")
            {
                val["现金金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A002")
            {
                val["票据张数"] = qro->value("tot_cost").toString();
            }

            blcn = qro->value("blance_no").toString();
        }

        //last record
        sq = "insert into tmp_balance_opb (操作员, 起始时间, 截止时间, 日结时间, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额)";
        sq += " values ('";
        sq += val["操作员"] + "','";
        sq += val["起始时间"] + "','";
        sq += val["截止时间"] + "','";
        sq += val["日结时间"] + "','";
        sq += val["票据张数"] + "','";
        sq += QString::asprintf("%.2f", amount) + "','";
        sq += val["现金金额"] + "','";
        sq += val["账户金额"] + "','";
        sq += val["统筹金额"] + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","last record 插入 tmp_balance_opb 明细 发生错误！\n" + qrm->lastError().text());
            qDebug()<<"插入 tmp_balance_opb 发生错误！";
            qDebug()<< qrm->lastError().text();
            qDebug()<<sq;
            return;
        }

        //inser sub_amount
        sq = " select  oper_name,oper_code,invoice_no, sum(tot_cost) tot_cost from fin_opb_daybalance "
             " where invoice_no in('A015','A016','A023','A002') " + dateRange + tmp;
        sq += " group by oper_name, oper_code, invoice_no order by oper_code";
        qDebug()<<"select sub_amount data :"<<sq;
        qro->exec(sq);
        amount = 0;
        first = true;      //首次进入循环
        QString opcd = "";
        while(qro->next())
        {
            if(opcd != qro->value("oper_code").toString() )
            {
                if(first)
                {
                    first = false;
                }
                else
                {
                    sq = "insert into tmp_balance_opb (操作员, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额)";
                    sq += " values ('";
                    sq += val["操作员"] + "','";
                    sq += val["票据张数"] + "','";
                    sq += QString::asprintf("%.2f", amount) + "','";
                    sq += val["现金金额"] + "','";
                    sq += val["账户金额"] + "','";
                    sq += val["统筹金额"] + "')";
                    if(!qrm->exec(sq))
                    {
                        QMessageBox::information(this,"注意","in cycle 插入 tmp_balance_opb 个人合计 发生错误！\n" + qrm->lastError().text());
                        qDebug()<<"插入 tmp_balance_opb 发生错误！";
                        qDebug()<< qrm->lastError().text();
                        qDebug()<<sq;
                        return;
                    }
                }
                val.clear();
                val["现金金额"] = "0";
                val["账户金额"] = "0";
                val["统筹金额"] = "0";
                amount = 0;
                val["操作员"] = qro->value("oper_name").toString() + " - 合计";
            }

            if(qro->value("invoice_no").toString() == "A015")
            {
                val["账户金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A016")
            {
                val["统筹金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A023")
            {
                val["现金金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A002")
            {
                val["票据张数"] = qro->value("tot_cost").toString();
            }

            opcd = qro->value("oper_code").toString();
        }

        //last record
        sq = "insert into tmp_balance_opb (操作员, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额)";
        sq += " values ('";
        sq += val["操作员"] + "','";
        sq += val["票据张数"] + "','";
        sq += QString::asprintf("%.2f", amount) + "','";
        sq += val["现金金额"] + "','";
        sq += val["账户金额"] + "','";
        sq += val["统筹金额"] + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","last recorder 插入 tmp_balance_opb 个人合计 发生错误！\n" + qrm->lastError().text());
            qDebug()<<"插入 tmp_balance_opb 发生错误！";
            qDebug()<< qrm->lastError().text();
            qDebug()<<sq;
            return;
        }

        //insert amount
        sq = " select  invoice_no, sum(tot_cost) tot_cost  from fin_opb_daybalance "
             " where invoice_no in('A015','A016','A023','A002') " + dateRange + tmp;
        sq += " group by invoice_no";
        qDebug()<<"select all_amount data :"<<sq;
        qro->exec(sq);
        amount = 0;
        val.clear();
        val["现金金额"] = "0";
        val["账户金额"] = "0";
        val["统筹金额"] = "0";
        while(qro->next())
        {

            if(qro->value("invoice_no").toString() == "A015")
            {
                val["账户金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A016")
            {
                val["统筹金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A023")
            {
                val["现金金额"] = QString::asprintf("%.2f", qro->value("tot_cost").toDouble());
                amount += qro->value("tot_cost").toDouble();
            }
            else if(qro->value("invoice_no").toString() == "A002")
            {
                val["票据张数"] = qro->value("tot_cost").toString();
            }
        }

        sq = "insert into tmp_balance_opb (操作员, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额)";
        sq += " values ('总合计','";
        sq += val["票据张数"] + "','";
        sq += QString::asprintf("%.2f", amount) + "','";
        sq += val["现金金额"] + "','";
        sq += val["账户金额"] + "','";
        sq += val["统筹金额"] + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","插入 tmp_balance_opb 总合计 发生错误！\n" + qrm->lastError().text());
            qDebug()<<"插入 tmp_balance_opb 发生错误！";
            qDebug()<< qrm->lastError().text();
            qDebug()<<sq;
            return;
        }
        //remove invalid data
        //sq = "delete from tmp_balance_opb where 票据张数 = ''";
        //qrm->exec(sq);
qDebug()<<sq;
        sq = "select 操作员, 起始时间, 截止时间, 票据张数, 合计金额, 现金金额, 账户金额, 统筹金额, ord"
             " from tmp_balance_opb order by ord"; // 日结时间,
        mdList.setQuery(sq, pub::db_m);

        if(mdList.rowCount()<1)
        {
            QMessageBox::information(this,"注意","指定的时间范围无数据！");
            ui->tvDetail_2->setModel(NULL);
        }
        else
        {
            ui->tvDetail_2->setModel(&mdList);
            int width = ui->tvDetail_2->width();
            pub::setColumnWidth(ui->tvDetail_2, "0.12^0.15^0.15^0.1^0.1^0.1^0.1^0.1", width);
        }

    }
}

void Form_gzltj::on_pbQuery_3_clicked()
{

    sql_for_print = "";

    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }

    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString dateRangeF = " and fee_date >= to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRangeF += " and fee_date <= to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";
    QString dateRangeR = " and reg_date >= to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRangeR += " and reg_date <= to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    QString tmpF,tmpR ;
    if(ui->cbbDept->currentText() != "全部" && ui->cbbDept->currentText() != "只看科室")
    {
        tmpF = " and doct_dept = '" + dept_code[ui->cbbDept->currentText()] + "' ";
        tmpR = " and (see_dpcd = '" + dept_code[ui->cbbDept->currentText()]
                + "' or dept_code = '" + dept_code[ui->cbbDept->currentText()] + "' ) ";
    }else
    {
        tmpF = "";
        tmpR = "";
    }

    //clear last query value
    qrm->exec("delete from tmp_feedetail");

    //检索诊室，医生收费汇总
    QStringList fee_names;
    sq = "SELECT DOCT_DEPT, doct_code, fun_get_minfee_name (fee_code) AS fee_name, SUM (Own_Cost) AS tot_fee";
    sq += " FROM fin_opb_feedetail WHERE 1 = 1 " + dateRangeF + tmpF;
    sq += " GROUP BY DOCT_DEPT, doct_code, fee_code";  //
    sq += " union ";
    sq += " SELECT dept_code, doct_code, fee_name, SUM (tot_fee) FROM";
    sq += " ( SELECT ( CASE WHEN see_dpcd IS NULL THEN DEPT_CODE ELSE SEE_DPCD END) DEPT_CODE,";
    sq += " ( CASE WHEN see_docd IS NULL THEN DOCT_CODE ELSE see_docd END ) DOCT_CODE,";
    sq += " '挂号诊察' fee_name, (diag_fee) AS tot_fee ";
    sq += " FROM fin_opr_register WHERE 1 = 1 " +dateRangeR + tmpR + ")";
    sq += " GROUP BY dept_code, doct_code, fee_name ";

    qDebug()<<"检索收费汇总 : "<< sq;
    qro->exec(sq);
    bool hasValue = false;
    while(qro->next()){
        hasValue = true;
        sq = "update tmp_feedetail set ";
        sq += qro->value("fee_name").toString() + " = '";
        sq += QString::asprintf("%.2f", qro->value("tot_fee").toDouble()) +  "'";
        sq += " where dept_code = '" + qro->value("doct_dept").toString() ;
        sq += "' and doct_code = '" + qro->value("doct_code").toString() + "'";
        qDebug()<<"try update tmp_feedetail : "<<sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "更新 tmp_feedetail sql执行错误！\n" + qrm->lastError().text());
            qDebug()<<"更新 tmp_feedetail sql执行错误！" + qrm->lastError().text();
            return;
        }
        if(qrm->numRowsAffected() < 1)
        {
            //update return falure, try to  insert
            sq = "insert into tmp_feedetail (dept_code, doct_code, " + qro->value("fee_name").toString();
            sq += " ) values ('";
            sq += qro->value("doct_dept").toString() + "','";
            sq += qro->value("doct_code").toString() + "','";
            sq += QString::asprintf("%.2f", qro->value("tot_fee").toDouble()) + "')";
            qDebug()<<"try insert tmp_feedetail : "<<sq;
            if(!qrm->exec(sq))
            {
                QMessageBox::information(this, "注意", "插入 tmp_feedetail sql执行错误！\n" + qrm->lastError().text());
                qDebug()<<"插入 tmp_feedetail sql执行错误！" + qrm->lastError().text();
                return;
            }
        }
    }
    if(!hasValue)
    {
        QMessageBox::information(this, "注意", "指定日期范围无数据！" );
        return;
    }

    //补齐医生姓名
    qrm->exec("update tmp_feedetail f set f.doct_name = (select empl_name from com_employee c where c.empl_code = f.doct_code limit 1)");
    //补齐医生科室
    qrm->exec("update tmp_feedetail f set f.dept_name = (select dept_name from com_department d where d.dept_code = f.dept_code limit 1)");

    //字段列表
    QString val_str ,field_str, sum_str;
    sq = "select name from com_dict_com where dic_type = 'MINFEE'";
    qrm->exec(sq);

    while(qrm->next())
    {
        sum_str += " , sum(" + qrm->value(0).toString() + " ) as " + qrm->value(0).toString() ;
        field_str += ", " + qrm->value(0).toString();
    }

    //保存最大索引值，不需要显示明细时，用来删除明细
    QString max_ord;

    qrm->exec("select max(ord) from tmp_feedetail");
    qrm->next();
    max_ord = qrm->value(0).toString();

    //科室汇总,全院汇总

    sq = " select dept_name " + sum_str + " from tmp_feedetail group by dept_name";
    qDebug()<<"科室汇总 : " << sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "科室汇总 sql执行错误！\n" + qrm->lastError().text());
        qDebug()<<"科室汇总 sql执行错误！" + qrm->lastError().text();
        return;
    }

    //get table field names
    QStringList field_names;
    for(int i = 0; ;i++)
    {
        QString fldnm = "";
        fldnm = qrm->record().fieldName(i);
        if(fldnm.isEmpty())
        {
            break;
        }
        else
        {
            field_names << fldnm;
        }
    }
    qDebug()<<"get table field names is : " << field_names;

    while(qrm->next())
    {
        field_str = "dept_name ";
        val_str = "'" + qrm->value("dept_name").toString() + "汇总'";
        for(int i = 1; i< field_names.size(); i++)
        {
            QString val = QString::asprintf("%.2f", qrm->value(field_names[i]).toDouble());
            if(val == "0.00")
            {
                val = "";
            }
            field_str += ", " + field_names[i] ;
            val_str += ", '" + val + "'";
        }
        sq = "insert into tmp_feedetail (" + field_str + ") values (" + val_str + ")";
        qDebug()<<"插入科室汇总 : " << sq;
        if(!qrmp->exec(sq))
        {
            QMessageBox::information(this, "注意", "插入科室汇总操作失败！\n" + qrmp->lastError().text());
            qDebug()<<"插入科室汇总操作失败！" + qrmp->lastError().text();
            return;
        }

    }

    //全院汇总

    sq = " select '全院汇总' " + sum_str + " from tmp_feedetail group by '全院汇总'";
    qDebug()<<"全院汇总 : " << sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "全院汇总 sql执行错误！\n" + qrm->lastError().text());
        qDebug()<<"全院汇总 sql执行错误！" + qrm->lastError().text();
        return;
    }

    qrm->next();
    QString last_fields;    //最终显示的非 0 字段，
    QString count_fields;   //参与计算合计的字段
    field_str = "dept_name ";
    //last_fields = "concat(concat(dept_name ,' - '), nvl(doct_name, '')) 诊室医生 ";
    last_fields = "dept_name  诊室医生 ";
    val_str = "'全院汇总'";
    for(int i = 1; i< field_names.size(); i++)
    {
        QString val = QString::asprintf("%.2f", qrm->value(field_names[i]).toDouble() / 2);
        field_str += ", " + field_names[i] ;
        val_str += ", '" + val + "'";
        if(val != "0.00")
        {
            last_fields += ", " + field_names[i] ;
            count_fields += " + (case when " + field_names[i] + " is null then 0 else " + field_names[i] + " end)";
        }
    }
    sq = "insert into tmp_feedetail (" + field_str + ") values (" + val_str + ")";
    qDebug()<<"插入全院汇总 : " << sq;
    if(!qrmp->exec(sq))
    {
        QMessageBox::information(this, "注意", "插入全院汇总操作失败！\n" + qrmp->lastError().text());
        qDebug()<<"插入全院汇总操作失败！" + qrmp->lastError().text();
        return;
    }

    //计算合计
    sq = "update tmp_feedetail set 合计 = 0 " + count_fields;
    qDebug()<<"计算合计 : "<<sq;
    qrm->exec(sq);
    //合并诊室+医生
    sq = "update tmp_feedetail set dept_name = concat(concat(dept_name ,' - '), doct_name) where doct_name is not null";
    qDebug()<<"合并诊室+医生 : "<<sq;
    qrm->exec(sq);

    //只看科室汇总，删除明细数据
    if(ui->cbbDept->currentText() == "只看科室")
    {
        ui->pbPrintCount->setEnabled(true);
        qrm->exec("delete from tmp_feedetail where ord <= " + max_ord);
    }
    else
    {
        ui->pbPrintCount->setEnabled(false);
    }

    sq = "select " + last_fields + ", format(合计, 2) 合计 from tmp_feedetail order by ord";
    sql_for_print = sq;

    mmdList = new MySqlModel(this, pub::db_m);

    qrm->exec(sq);

    mmdList->setQuery(*qrm);

    ui->tvDetail_3->setModel(mmdList);

    double width = ui->tvDetail_3->width() - 50;
    //ui->tvDetail_3->setModel(&mdList);

    pub::setColumnWidth(ui->tvDetail_3, "0.12^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08", width,20);


}

void Form_gzltj::on_pbQuery_4_clicked()
{
    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }

    //clear last query value
    qro->exec("delete from tmp_si_query");

    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString dateRange = " and oper_date >= to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRange += " and oper_date <= to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    QString tmp;
    if(ui->cbbInsuType->currentText() != "全部"  )
    {
        tmp = " and insutype = '" + insutype_code[ui->cbbInsuType->currentText()] + "' ";

    }else
    {
        tmp = "";

    }

    //提取指定日期数据
    sq = "insert into tmp_si_query";
    sq += " select mcard_no , name, invoice_no , dept_name, oper_date, tot_cost, pub_cost, pay_cost,own_cost,med_type, "
         " insutype,psn_type from FIN_IPR_SIINMAININFO where 1 = 1 " + dateRange + tmp;

    qDebug()<< "select data from fin_ipr_siinmaininfo : " << sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "提取 fin_ipr_siinmaininfo 数据执行错误！\n" + qro->lastError().text());
        qDebug()<<"select data from fin_ipr_siinmaininfo。 " + qro->lastError().text();
        return;
    }


    //计算汇总数据
    sq = "insert into tmp_si_query (mcard_no, tot_cost, pub_cost, pay_cost,own_cost )";
    sq += "select '合计',sum(tot_cost) , sum(pub_cost) , sum( pay_cost) , sum(own_cost) from FIN_IPR_SIINMAININFO where 1 = 1 "
            + dateRange + tmp;
    qDebug()<<"计算汇总数据 : "<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "提取 fin_ipr_siinmaininfo 汇总数据执行错误！\n" + qro->lastError().text());
        qDebug()<<"select data from fin_ipr_siinmaininfo。 " + qro->lastError().text();
        return;
    }

    qDebug()<<"process inustype";
    sq = "select distinct insutype from tmp_si_query";
    qro->exec(sq);
    while(qro->next())
    {
        sq = "select name from com_dict_com where dic_type = '险种' and  code = '"+qro->value(0).toString()+"' ";
        qDebug()<<sq;
        qrmp->exec(sq);
        if(qrmp->next())
        {
            sq = "update tmp_si_query set insutype = '"+qrmp->value(0).toString()+"' where insutype = '"+qro->value(0).toString()+"'";
            qDebug()<<sq;
            qrot->exec(sq);
        }
    }

    qDebug()<<"process person type";
    sq = "select distinct psn_type from tmp_si_query";
    qro->exec(sq);
    while(qro->next())
    {
        sq = "SELECT dic_label from com_dict_new where dic_type = 'PSN_TYPE' and dic_value ='" + qro->value(0).toString() + "' ";
        qDebug()<<sq;
        qrmp->exec(sq);
        if(qrmp->next())
        {
            sq = "update tmp_si_query set psn_type = '"+qrmp->value(0).toString()+"' where psn_type = '"+qro->value(0).toString()+"'";
            qDebug()<<sq;
            qrot->exec(sq);
        }
    }

    sq = "select mcard_no 医保卡号, name 姓名 , invoice_no 发票号, dept_name 诊室, oper_date 费用时间, "
         "tot_cost 金额, pub_cost 统筹支付, pay_cost 账户支付,own_cost 现金支付, "
         "insutype  险种, psn_type  人员类别  from tmp_si_query order by oper_date";
    qDebug() << " display result : " << sq;
    mdList.setQuery(sq, pub::db_o);
    ui->tvDetail_4->setModel(&mdList);

}

void Form_gzltj::on_rbWrj_clicked()
{
//    if(ui->rbWrj->isChecked())
//    {
//        ui->dtBegin_5->setEnabled(false);
//        ui->dtEnd_5->setEnabled(false);
//    }else{
//        ui->dtBegin_5->setEnabled(true);
//        ui->dtEnd_5->setEnabled(true);
//    }
}

void Form_gzltj::on_rbBr_clicked()
{
    on_rbWrj_clicked();
}

void Form_gzltj::on_pbQuery_5_clicked()
{

    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }

    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString t = " and reg_date>=to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    t += " and reg_date<=to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    double width = ui->tvDetail_5->width() - 50;  //显示列表的宽度

    //用于刷新显示状态
    mdList.setQuery("select sysdate from dual", pub::db_o);
    ui->tvDetail_5->setModel(&mdList);

    if(ui->rb_clinic_count->isChecked())
    {
        sq = " select type 分类, count 数量 from "
             "( ( select '总人次' type, count(*) count from fin_opr_register where "
             " valid_flag = '1'  %1 )"
             " union "
             "( select concat('按收费类别：', pact_name) type, count(*) count "
             " from fin_opr_register where valid_flag = '1'  %1 group by pact_name ) "
             " union "
             "( select concat('按科室：',dept_name) type, count(*) count "
             " from fin_opr_register where valid_flag = '1'  %1 group by dept_name "
             " ) ）"
             " order by 分类 ";
        sq = sq.arg(t);

        qDebug()<<"门诊量统计："<<sq<<"\n";
        mdList.setQuery(sq, pub::db_o);
        ui->tvDetail_5->setModel(&mdList);
        pub::setColumnWidth(ui->tvDetail_5, "0.2^0.2^0", width);
    }
    else if(ui->rb_insu_code->isChecked())
    {
        if(ui->le_ag0->text().toInt()== 0 || ui->le_ag1->text().toInt() == 0)
        {
            QMessageBox::information(this, "注意", "年龄数字无效！");
            return;
        }

        if(ui->le_ag1->text().toInt() < ui->le_ag0->text().toInt())
        {
            QMessageBox::information(this, "注意", "起始年龄不应该大于截止年龄！");
            return;
        }

        sq = "SELECT jyfs 交易方式, sum(cnt) 累计人次 from "
             "(  select count(*) cnt, jyfs,"
             "     ROUND(  "   //从入参提取患者出生日期，通过交易时间计算时间差做为年龄
             "       DATEDIFF( "
             "         STR_TO_DATE(SUBSTR(jysj FROM 1 FOR 10) ,'%Y-%m-%d'),"
             "         STR_TO_DATE(SUBSTR(v_in from POSITION('certno' IN v_in) + 15 FOR 10),'%Y%m%d')"
             "               )"
             "       /365.25 "
             "      ) ag "
             "  from com_business  "
             "  where ywbh = '1101' and jyfs is not null "
             "  and LEFT(jysj,10) >= '%1' and LEFT(jysj,10) <= '%2'"
             "  group by jyfs, ag"
             ") base"
             " where ag >= %3 and ag <= %4 "
             " GROUP BY jyfs ";

        sq = sq.arg(begin.left(10)).arg(end.left(10));
        sq = sq.arg(ui->le_ag0->text()).arg(ui->le_ag1->text());

        qDebug()<<"查询电子医保码使用率："<<sq<<"\n";
        mdList.setQuery(sq, pub::db_m);
        ui->tvDetail_5->setModel(&mdList);
        pub::setColumnWidth(ui->tvDetail_5, "0.2^0.2^0", width);
    }
    else if(ui->rb_card_no_invoice_no->isChecked())
    {
        if(ui->le_card_no->text().trimmed().isEmpty())
        {
            QMessageBox::information(this, "注意", "请输入需要查询的序列号！");
            return;
        }

        sq = "select card_no 病志号, clinic_code 门诊号, recipe_no 处方号, invoice_no 发票号,"
             " reg_date 挂号时间, item_name 项目名称,specs 规格, "
             " qty/pack_qty 数量, price_unit 单位, own_cost 金额" //name 患者姓名,
             " from fin_opb_feedetail where ";

        if(ui->cbb_sn_type->currentText() == "病志号")
        {
            sq += " card_no = '" + pub::add0( ui->le_card_no->text().trimmed(), 10) + "' ";
        }
        else if(ui->cbb_sn_type->currentText() == "门诊号")
        {
            sq += " clinic_code = '" + ui->le_card_no->text().trimmed() + "' ";
        }
        else if(ui->cbb_sn_type->currentText() == "处方号")
        {
            sq += " recipe_no = '" + ui->le_card_no->text().trimmed() + "' ";
        }
        else if(ui->cbb_sn_type->currentText() == "发票号")
        {
            sq += " invoice_no = '" + pub::add0( ui->le_card_no->text().trimmed(), 12) + "' ";
        }

        sq += " and pay_flag = '1' and cancel_flag = '1' order by reg_date, oper_date";

        qDebug()<<"病志、门诊、处方、发票号码互查："<<sq<<"\n";

        mdList.setQuery(sq, pub::db_o);
        ui->tvDetail_5->setModel(&mdList);
        pub::setColumnWidth(ui->tvDetail_5, "0.09^0.09^0.09^0.09^0.12^0.15^0.1^0.05^0.05^0.05", width);

    }
    //ui->tvDetail_5->setModel(&mdList);
}

void Form_gzltj::on_pbPrintCount_clicked()
{
    ui->pbPrintCount->setEnabled(false);
    qrm->exec(sql_for_print);   //当前显示的查询结果
    QSqlRecord rcd = qrm->record();     //为提取字段标题

    QJsonDocument d;
    QJsonArray jsa_val;    //数值

    QJsonObject jot;  // 临时json
    int row = 3;

    int rowCount = 0;
    int columnCount = 0;

    //提取字段名称
    for(int i = 0; ; i++)
    {
        if(rcd.fieldName(i).isEmpty())
        {
            columnCount = i;
            break;
        }
        else
        {
            QString itm = rcd.fieldName(i);
            //最左侧列，字串整理
            if(i == 0 )
            {
                itm = itm.mid(0, itm.length() - 2);
            }
            jot.insert("val", itm);
            jot.insert("row", row);
            jot.insert("col", i + 1 );
            jsa_val << jot;
        }
    }

    if(rowCount > 20)
    {
        QMessageBox::information(this, "注意", "统计列数不允许超过20个！");
        return;
    }

    row++;

    while(qrm->next())
    {
        rcd = qrm->record();

        for(int i = 0; ; i++)
        {
            if(rcd.fieldName(i).isEmpty())
            {
                break;
            }
            else
            {
                QString itm = rcd.value(i).toString();
                //最左侧列，字串整理
                if(i == 0 )
                {
                    itm = itm.mid(0, itm.length() - 2);
                }
                jot.insert("val", itm);
                jot.insert("row", row);
                jot.insert("col", i + 1 );
                jsa_val << jot;
            }
        }

        row ++;
        rowCount ++ ;

    }

    QString time_range;
    time_range = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    time_range += " 至 ";
    time_range += ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    jot.insert("val", "统计时间：" + time_range);
    jot.insert("row", 2);
    jot.insert("col", 1);
    jsa_val << jot;

    jot.insert("val", "打印时间：" + QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    jot.insert("row", row );
    jot.insert("col", 1);
    jsa_val << jot;

    QJsonArray jsa_clr;    //清除区域,按最大不可能估算，30个科室，25种收费项目
    jot = d.object();
    jot.insert("row1", 3);
    jot.insert("row2", 30);
    jot.insert("col1", 1);
    jot.insert("col2", 25);
    jsa_clr << jot;

    QJsonArray jsa_rng;    //表格区域
    jot = d.object();
    char col = 'A' + columnCount - 1;
    QString rg = QString("A3:%1%2").arg(QString(col)).arg(QString::number( rowCount + 3 ));
    jot.insert("range", rg);
    jsa_rng << jot;

    QJsonArray jsa_merge;    //需要合并的区域
    jot = d.object();
    rg = QString("A1:%1%2").arg(QString(col)).arg(QString::number(1));
    jot.insert("range", rg);
    jsa_merge << jot;


    QJsonArray jsa_col_w;    //需要单独设置的列宽
    jot = d.object();
    rg = QString("%1%2:%1%2").arg(QString(col)).arg(QString::number(1));
    jot.insert("range", rg);
    jot.insert("width", 15);
    jsa_col_w << jot;

    rg = QString("A1:A1");
    jot.insert("range", rg);
    jot.insert("width", 15);
    jsa_col_w << jot;

    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/menzhenyueshouru.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("grid_range", jsa_rng);

    jo.insert("merge_range", jsa_merge);
    jo.insert("col_width", jsa_col_w);

    pub::printOutExcel(jo);

}

void Form_gzltj::on_tb_begin_clicked()
{
    int t = ui->tb_begin->pos().y() + this->pos().y();
    int l = ui->tb_begin->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->dte_begin->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();

    ui->dte_begin->setDate(dlg_get_date->ret_date());
}

void Form_gzltj::on_tb_end_clicked()
{
    int t = ui->tb_end->pos().y() + this->pos().y();
    int l = ui->tb_end->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->dte_end->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();
    ui->dte_end->setDate(dlg_get_date->ret_date());
}

void Form_gzltj::on_pb_run_fee_detail_clicked()
{
    if(ui->dte_end->dateTime() <= ui->dte_begin->dateTime())
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return;
    }

    if((ui->rb_title_dept->isChecked() || ui->rb_title_item->isChecked())
            && (ui->rb_none_0->isChecked() || ui->rb_none_1->isChecked()))
    {
        QMessageBox::information(this,"注意","未选择常规列表字段，相关字段必须进行汇总！");
        return;
    }

    dlg_delay->setText("正在提取数据。。。");
    dlg_delay->setModal(true);
    dlg_delay->setNeedClose(false);
    dlg_delay->show();
    qApp->processEvents();

    QString begin = ui->dte_begin->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString end = ui->dte_end->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QString dateRangeF = " and fee_date >= to_date('" + begin + "','yyyy-mm-dd hh24:mi:ss') ";
    dateRangeF += " and fee_date <= to_date('" + end + "','yyyy-mm-dd hh24:mi:ss') ";

    QString tmpF = "";
    QString tmp_c, tmp_l; //combobox , lineedit
    QStringList tmp_list; //
    //诊室
    tmp_c = ui->cbb_dept_fee_detail->currentText();
    tmp_l = ui->le_dept_list->text().trimmed();

    if( tmp_c != "全部" && tmp_l != "全部")
    {
        tmp_list = (tmp_c + "^" + tmp_l).split("^");
        tmp_l = "'tmp'";  //简化算法，前置无效数据

        foreach(QString s, tmp_list)
        {
            if(s.trimmed().isEmpty())
            {
                continue;
            }
            tmp_l.append(",'");
            tmp_l.append(dept_code[s]);
            tmp_l.append("'");
        }

        tmpF += " and fin.reg_dpcd in (" + tmp_l + ") ";
    }

    //医生
    tmp_c = ui->cbb_doct_fee_detail->currentText();
    tmp_l = ui->le_doct_list->text().trimmed();

    if( tmp_c != "全部" && tmp_l != "全部")
    {
        QString str = get_code_from_str(doct_code_rela, tmp_c, tmp_l);
        tmpF += " and fin.doct_code in (" + str + ") ";
    }

    //收费类别
    tmp_c = ui->cbb_fee_type->currentText();
    tmp_l = ui->le_type_list->text().trimmed();

    if(tmp_c != "全部" && tmp_l != "全部")
    {
        QString str = get_code_from_str(fee_code_rela, tmp_c, tmp_l);
        tmpF += " and fin.fee_code in (" + str + ") ";
    }

    //项目名称
    if(!ui->le_item_name_key->text().trimmed().isEmpty())
    {
        tmpF += " and fin.item_name like '%" + ui->le_item_name_key->text().trimmed() + "%' ";
    }


    //按筛选条件提取基本数据
    QString base_sql ;

    if(ui->ckb_group_name->isChecked())
    {
        base_sql = " (select "
                   " reg.dept_name, "
                   " emp.empl_name,"
                   " '组合' fee_name,"
                   " package_name item_name, "
                   " '-' specs,"
                   " 1 unit_price, "
                   " '次' price_unit,"
                   " 1 qty, "
                   " sum(fin.own_cost) own_cost,"
                   " reg.name, "
                   " to_char(fin.fee_date, 'yyyy-mm-dd') regdt,"
                   " reg.card_no,"
                   " reg.pact_name"
                   " from fin_opb_feedetail fin "
                   " LEFT JOIN FIN_OPR_REGISTER reg on REG.clinic_code = FIN.CLINIC_CODE "
                   " left join COM_EMPLOYEE emp on emp.empl_code = fin.doct_code "
                   " where 1 = 1 "
                + dateRangeF
                + tmpF
                + " and pay_flag = '1' and cancel_flag = '1'"
                  " group by"
                  " reg.dept_name, emp.empl_name, fin.package_name,"
                  " reg.name, to_char(fin.fee_date, 'yyyy-mm-dd'),"
                  " reg.card_no,reg.pact_name,fin.recipe_no "
                  " ) base";
    }
    else
    {
    base_sql = " (SELECT "
               " REG.dept_name, "
               " emp.empl_name, "
               " fun_get_minfee_name (fee_code) AS fee_name,"
               " fin.item_name, "
               " FIN.specs,"
               " FIN.unit_price, "
               " FIN.price_unit, "
               " FIN.qty / FIN.PACK_QTY qty, "
               " FIN.own_cost, "
               " REG.name, "
               " to_char(fin.fee_date, 'yyyy-mm-dd') regdt,"
               " reg.card_no,"
               " reg.pact_name"
               " FROM fin_opb_feedetail fin "
               " LEFT JOIN FIN_OPR_REGISTER reg on REG.clinic_code = FIN.CLINIC_CODE "
               " left join COM_EMPLOYEE emp on emp.empl_code = fin.doct_code "
               " where 1 = 1 "
            + dateRangeF
            + tmpF
            + " and pay_flag = '1' and cancel_flag = '1') base";
    }

    qDebug()<<"base_sql : "<<base_sql;

    //按汇总条件从基本数据中再次提取
    QString grp = "";
    QString fld = "";

    if(ui->rb_item->isChecked())
    {
        //按项目
        if(ui->rb_dept->isChecked())
        {
            //项目 + 诊室
            grp = " group by dept_name, fee_name,item_name ";
            fld = " dept_name 诊室, '' 医生, fee_name 费别, item_name 项目名称, "
                  " max(specs) 规格, max(unit_price) 价格, max(price_unit) 单位, "
                  " sum(qty) 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期, '' 病志号, '' 交费方式 ";
        }else if(ui->rb_doct->isChecked())
        {
            //项目 + 医生
            grp = " group by dept_name, empl_name, fee_name,item_name ";
            fld = " dept_name 诊室, empl_name 医生, fee_name 费别, item_name 项目名称, "
                  " max(specs) 规格, max(unit_price) 价格, max(price_unit) 单位, "
                  " sum(qty) 数量, to_char(sum(own_cost)) 金额,"
                   "'' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }
        else
        {
            //仅项目
            grp = " group by fee_name, item_name ";
            fld = " '' 诊室, '' 医生, fee_name 费别, item_name 项目名称, max(specs) 规格,"
                  " max(unit_price) 价格, max(price_unit) 单位, sum(qty) 数量, "
                  " to_char(sum(own_cost)) 金额,'' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }

    }
    else if(ui->rb_fee->isChecked())
    {
        //按收费类
        if(ui->rb_dept->isChecked())
        {
            //收费类 + 诊室
            grp = " group by dept_name, fee_name ";
            fld = " dept_name 诊室, '' 医生, fee_name 费别, '' 项目名称, '' 规格,"
                  " '' 价格, '' 单位, '' 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }
        else if(ui->rb_doct->isChecked())
        {
            //收费类 + 医生
            grp = " group by dept_name, empl_name, fee_name ";
            fld = " dept_name 诊室, empl_name 医生, fee_name 费别, '' 项目名称, '' 规格,"
                  " '' 价格, '' 单位, '' 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }
        else
        {
            //仅收费类
            grp = " group by fee_name ";
            fld = " '' 诊室, '' 医生, fee_name 费别, '' 项目名称, '' 规格,"
                  " '' 价格, '' 单位, '' 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }

    }
    else
    {
        //不按项目和收费类汇总
        if(ui->rb_dept->isChecked())
        {
            // 诊室
            grp = " group by dept_name ";
            fld = " dept_name 诊室, '' 医生, '' 费别, '' 项目名称, '' 规格,"
                  " '' 价格, '' 单位, '' 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }else if(ui->rb_doct->isChecked()){
            // 医生
            grp = " group by dept_name, empl_name ";
            fld = " dept_name 诊室, empl_name 医生, '' 费别, '' 项目名称, '' 规格,"
                  " '' 价格, '' 单位, '' 数量, to_char(sum(own_cost)) 金额,"
                  " '' 患者姓名,'' 就诊日期 , '' 病志号, '' 交费方式";
        }else{
            //不汇总
            grp = " ";
            fld = " dept_name 诊室, empl_name 医生, fee_name 费别, item_name 项目名称, specs 规格,"
                  " unit_price 价格, price_unit 单位, qty 数量, own_cost 金额,"
                  " name 患者姓名,regdt 就诊日期 , card_no 病志号, pact_name 交费方式";
        }
    }

    sq = " select " + fld + " from " + base_sql + grp + " order by 就诊日期, 诊室,医生,费别,项目名称";

    qDebug()<<"normal final sql  : "<<sq;

    QString tmp_sql;

    if(ui->rb_title_normal->isChecked())
    {
        //正常字段输出
        md_fee_detail->setQuery(sq, pub::db_o);
        ui->tv_fee_detail->setModel(md_fee_detail);
    }
    else
    {
        QString sum_fields;
        QStringList fields;

        if(ui->rb_title_dept->isChecked())
        {
            //诊室、医生做为列表字段
            fields = get_fields(sq, "concat(诊室,医生)", sum_fields);
        }
        else
        {
            //费别、项目做为列表字段
            if(ui->rb_fee->isChecked())
            {
                fields = get_fields(sq, "费别", sum_fields);
            }
            else
            {
                fields = get_fields(sq, "项目名称, 费别", sum_fields);
            }
            //fields = get_fields(sq, "concat(费别, 项目名称)", sum_fields);
        }

        //按所需字段建立临时表
        if(!create_temp_table(fields))
        {
            dlg_delay->setNeedClose(true);
            dlg_delay->closeWindow();
            return;
        }

        //提取数据向临时表填充
        tmp_sql = " select dest.费别, dest.项目名称, dest.诊室, dest.医生,"
                  " dest.数量 , dest.金额 "
                  " from (" + sq + ") dest";

        qrot->exec(tmp_sql);

        if(!qrot->next())
        {
            QMessageBox::information(this, "注意", "查询无结果！");

            dlg_delay->setNeedClose(true);
            dlg_delay->closeWindow();
            return;
        }

        while(true)
        {
            tmp_sql = "insert into tmp_work_count (base_field, " ;

            if(ui->rb_title_dept->isChecked())
            {
                //诊室、医生做为列表字段
                tmp_sql += "`" + qrot->value("诊室").toString();
                tmp_sql += qrot->value("医生").toString() + "`";
                tmp_sql += " ) values (";
                tmp_sql += "'" + qrot->value("费别").toString();
                tmp_sql += qrot->value("项目名称").toString() + "',";
                if(ui->rb_fee_amount->isChecked())
                {
                    tmp_sql += qrot->value("金额").toString() ;
                }
                else
                {
                    tmp_sql += qrot->value("数量").toString() ;
                }
            }
            else
            {
                //费别、项目做为列表字段
                if(ui->rb_fee->isChecked())
                {
                    tmp_sql += "`" + qrot->value("费别").toString() + "`";
                }
                else
                {
                    tmp_sql += "`" + qrot->value("项目名称").toString() + "`";
                }
                //tmp_sql += "`" + qrot->value("费别").toString();
                //tmp_sql += qrot->value("项目名称").toString() + "`";
                tmp_sql += " ) values (";
                tmp_sql += "'" + qrot->value("诊室").toString();
                tmp_sql += qrot->value("医生").toString() + "',";

                if(ui->rb_fee_amount->isChecked())
                {
                    tmp_sql += qrot->value("金额").toString() ;
                }
                else
                {
                    tmp_sql += qrot->value("数量").toString() ;
                }
            }

            tmp_sql += ")";

            qrm->exec(tmp_sql);

            if(!qrot->next())
            {
                break;
            }
        }

        sq = "select base_field " + sum_fields + " from tmp_work_count group by base_field";

        md_fee_detail->setQuery(sq, pub::db_m);
        ui->tv_fee_detail->setModel(md_fee_detail);

    }

    dlg_delay->setNeedClose(true);
    dlg_delay->closeWindow();
    last_sql = sq;
    qDebug()<<"检索收费数据 : "<< sq;

    ui->pb_export_to_excel->setEnabled(true);

}

bool Form_gzltj::create_temp_table(QStringList flds)
{
    int fld_size = flds.size() ;
    if( fld_size < 1)
    {
        QMessageBox::information(this, "注意", "字段数据为空 ! ");
        return false;
    }

    if(fld_size > MAX_EXPORT_FIELD_COUNT)
    {
        QMessageBox::information(this, "注意", "字段数量"
                                 + QString::number(fld_size)
                                 + ", 超过最大限制 "
                                 + QString::number(MAX_EXPORT_FIELD_COUNT)
                                 + " ! ");
        return false;
    }

    QString tmp_sql;
    tmp_sql = "drop table if exists tmp_work_count";

    if(!qrm->exec(tmp_sql))
    {
        QMessageBox::information(this, "注意", "无法删除临时数据表 tmp_work_count ! ");
        return false;
    }

    tmp_sql = " create temporary table tmp_work_count (base_field varchar(50) ,";

    foreach(QString s , flds)
    {
        if(s.isEmpty())
        {
            QMessageBox::information(this, "注意", "原始数据不完整，出现空白字段无法继续计算 ! ");
            return false;
        }

        s = "`" + s + "`";
        tmp_sql.append(s);
        tmp_sql.append(" DECIMAL(10,2),");
    }

    //末尾 "," 替换为 ")"
    tmp_sql.replace(tmp_sql.length() - 1, 1, ")");

    qDebug()<<"建立临时表："<<tmp_sql;
    if(!qrm->exec(tmp_sql))
    {
        QMessageBox::information(this, "注意", "无法创建临时数据表 tmp_work_count ! ");
        return false;
    }

    return true;

}

QStringList Form_gzltj::get_fields(QString sql, QString field_name, QString &sum)
{
    QStringList ret_lst;

    QString tmp_sql = "select distinct " + field_name + " from (" + sql + ") ";

    if(ui->rb_title_item->isChecked() && ui->rb_item->isChecked() )
    {
        tmp_sql += " order by 费别";
    }

    if(ui->rb_title_dept->isChecked())
    {
        tmp_sql += " order by " + field_name;
    }

    qDebug()<<"get_fields sql : "<<tmp_sql;

    qrot->exec(tmp_sql);
    while(qrot->next())
    {
        ret_lst << qrot->value(0).toString();
        sum += ", sum(`" + qrot->value(0).toString() + "`) `"
                + qrot->value(0).toString() + "`";
    }

    return ret_lst;
}

void Form_gzltj::on_cbb_dept_fee_detail_currentTextChanged(const QString &arg1)
{
    if(!initial_finished)
    {
        return;
    }

    sq = "select name, LPAD(code, 6, '0') "
         " from com_privileges "
         " where type = 'dept' and role_dept = '" + arg1 + "'";

    qDebug()<<"提取诊室关联的医生："<<sq;

    ui->cbb_doct_fee_detail->clear();
    ui->cbb_doct_fee_detail->addItem("全部");

    doct_code_rela = pub::fillCombo(ui->cbb_doct_fee_detail, sq, 0, qrm, false);    //qro

    doct_code_rela = "全部^^" + doct_code_rela ;
}

void Form_gzltj::add_cbb_to_le(QComboBox *cbb, QLineEdit *le)
{

    QString cur_le = le->text().trimmed();
    QString cur_cbb = cbb->currentText();

    if(cur_cbb == "全部")
    {
        le->setText("全部");
        return;
    }

    if(cur_le.indexOf(cur_cbb) < 0)
    {
        if(cur_le.isEmpty())
        {
            le->setText(cur_cbb);
        }
        else
        {
            le->setText(cur_le + "^" + cur_cbb);
        }
    }

}
void Form_gzltj::on_pb_clear_condition_clicked()
{
    ui->cbb_dept_fee_detail->setCurrentIndex(0);
    //ui->cbb_doct_fee_detail->setCurrentIndex(0);
    ui->cbb_fee_type->setCurrentIndex(0);

    ui->le_dept_list->clear();
    ui->le_doct_list->clear();
    ui->le_type_list->clear();

    ui->le_item_name_key->clear();
}

void Form_gzltj::on_tb_add_dept_clicked()
{
    add_cbb_to_le(ui->cbb_dept_fee_detail,ui->le_dept_list);
}

void Form_gzltj::on_tb_add_doct_clicked()
{
    add_cbb_to_le(ui->cbb_doct_fee_detail, ui->le_doct_list);
}

void Form_gzltj::on_tb_add_type_clicked()
{
    add_cbb_to_le(ui->cbb_fee_type, ui->le_type_list);
}


QString Form_gzltj::get_code_from_str(QString base, QString cbb, QString le)
{
    QStringList tmp_list = (cbb + "^" + le).split("^");

    QString ret = "'tmp'";
    int pos;

    foreach(QString s, tmp_list)
    {
        if(s.trimmed().isEmpty())
        {
            continue;
        }

        ret.append(",'");
        pos = pub::searchStr(base, "^", s);
        ret.append(pub::getStr(base, "^", pos + 1));
        ret.append("'");
    }

    return ret;
}

void Form_gzltj::on_pb_export_to_excel_clicked()
{

    if(last_sql.isEmpty())
    {
        QMessageBox::information(this,"注意","无有效查询记录！");
        return;
    }

    ui->pb_export_to_excel->setEnabled(false);
    ui->pb_run_fee_detail->setEnabled(false);

    qApp->processEvents();

    if(ui->rb_title_dept->isChecked() || ui->rb_title_item->isChecked())
    {
        pub::export_sql_to_excel(last_sql, qrm);
    }
    else
    {
        pub::export_sql_to_excel(last_sql, qrot);
    }

    ui->pb_run_fee_detail->setEnabled(true);
    ui->pb_export_to_excel->setEnabled(true);
}

void Form_gzltj::on_rb_title_normal_clicked()
{
    if(ui->rb_title_normal->isChecked())
    {
        ui->grp_count_field->setEnabled(false);
        ui->ckb_group_name->setChecked(false);
        ui->ckb_group_name->setEnabled(false);
    }
    else
    {
        ui->grp_count_field->setEnabled(true);
        ui->ckb_group_name->setEnabled(true);
    }
}

void Form_gzltj::on_rb_title_dept_clicked()
{
    on_rb_title_normal_clicked();
}

void Form_gzltj::on_rb_title_item_clicked()
{
    on_rb_title_normal_clicked();
}

void Form_gzltj::on_pb_count_export_clicked()
{
    //
    if(sql_for_print.isEmpty())
    {
        QMessageBox::information(this,"注意","无有效查询记录！");
        return;
    }

    ui->pb_count_export->setEnabled(false);
    qApp->processEvents();

    pub::export_sql_to_excel(sql_for_print, qrm);

    ui->pb_count_export->setEnabled(true);
}
